or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

conversion.mddata-manipulation.mdevents.mdhashing.mdindex.mdjson-rpc.mdpromises.mdproviders.mdrandom-validation.md

random-validation.mddocs/

0

# Random Generation and Validation

1

2

Secure random value generation and validation utilities for cryptographic applications and data validation. These functions provide essential security and validation capabilities.

3

4

## Capabilities

5

6

### Random Value Generation

7

8

#### Random Bytes

9

10

```typescript { .api }

11

/**

12

* Returns random byte array of given size

13

* Uses cryptographically secure random number generation

14

* @param size - Number of bytes to generate

15

* @returns Cryptographically secure random Uint8Array

16

*/

17

function randomBytes(size: number): Uint8Array;

18

```

19

20

#### Random Hex

21

22

```typescript { .api }

23

/**

24

* Returns random hex string of given byte size

25

* Uses cryptographically secure random number generation

26

* @param byteSize - Number of bytes for the random value

27

* @returns Hex string prefixed with "0x"

28

*/

29

function randomHex(byteSize: number): string;

30

```

31

32

### UUID Generation

33

34

#### Version 4 UUID

35

36

```typescript { .api }

37

/**

38

* Generates version 4 (random) UUID

39

* Follows RFC 4122 specification for random UUIDs

40

* @returns UUID string in standard format (xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx)

41

*/

42

function uuidV4(): string;

43

```

44

45

### Data Validation

46

47

#### Type Guards

48

49

```typescript { .api }

50

/**

51

* Type guard for Uint8Array (including Node.js Buffer)

52

* Checks if data is Uint8Array or Buffer instance

53

* @param data - Data to check

54

* @returns true if data is Uint8Array or Buffer

55

*/

56

function isUint8Array(data: unknown | Uint8Array): data is Uint8Array;

57

```

58

59

### Deprecated Validation Functions

60

61

**Note**: Most validation functions are deprecated and will be removed in the next release. Use the `web3-validator` package instead.

62

63

```typescript { .api }

64

/**

65

* @deprecated Will be removed in next release. Use web3-validator package instead.

66

* Checks if value is strict hex string

67

*/

68

const isHexStrict: (value: unknown) => boolean;

69

70

/**

71

* @deprecated Will be removed in next release. Use web3-validator package instead.

72

* Checks if value is hex, number or bigint

73

*/

74

const isHex: (value: unknown) => boolean;

75

76

/**

77

* @deprecated Will be removed in next release. Use web3-validator package instead.

78

* Validates address checksum

79

*/

80

const checkAddressCheckSum: (address: string) => boolean;

81

82

/**

83

* @deprecated Will be removed in next release. Use web3-validator package instead.

84

* Checks if value is valid Ethereum address

85

*/

86

const isAddress: (address: unknown) => boolean;

87

88

/**

89

* @deprecated Will be removed in next release. Use web3-validator package instead.

90

* Checks if value is bloom filter

91

*/

92

const isBloom: (bloom: unknown) => boolean;

93

94

/**

95

* @deprecated Will be removed in next release. Use web3-validator package instead.

96

* Checks if value is in bloom filter

97

*/

98

const isInBloom: (bloom: string, value: string) => boolean;

99

100

/**

101

* @deprecated Will be removed in next release. Use web3-validator package instead.

102

* Checks if user Ethereum address is in bloom filter

103

*/

104

const isUserEthereumAddressInBloom: (bloom: string, address: string) => boolean;

105

106

/**

107

* @deprecated Will be removed in next release. Use web3-validator package instead.

108

* Checks if contract address is in bloom filter

109

*/

110

const isContractAddressInBloom: (bloom: string, address: string) => boolean;

111

112

/**

113

* @deprecated Will be removed in next release. Use web3-validator package instead.

114

* Checks if value is valid topic

115

*/

116

const isTopic: (topic: unknown) => boolean;

117

118

/**

119

* @deprecated Will be removed in next release. Use web3-validator package instead.

120

* Checks if topic is in bloom filter

121

*/

122

const isTopicInBloom: (bloom: string, topic: string) => boolean;

123

```

124

125

### Active Validation Functions

126

127

#### Block Number Comparison

128

129

```typescript { .api }

130

/**

131

* Compares block numbers/tags, returns comparison result

132

* Handles both numeric block numbers and special tags like 'latest', 'pending'

133

* @param blockA - First block number or tag

134

* @param blockB - Second block number or tag

135

* @returns -1 if blockA < blockB, 0 if equal, 1 if blockA > blockB

136

*/

137

function compareBlockNumbers(blockA: BlockNumberOrTag, blockB: BlockNumberOrTag): number;

138

```

139

140

#### Type Guards

141

142

```typescript { .api }

143

/**

144

* Type guard for contract initialization options

145

* @param options - Object to check

146

* @returns true if options match ContractInitOptions interface

147

*/

148

function isContractInitOptions(options: unknown): options is ContractInitOptions;

149

150

/**

151

* Re-exported from web3-validator

152

* Checks if value is null or undefined

153

*/

154

const isNullish: (value: unknown) => value is null | undefined;

155

```

156

157

## Usage Examples

158

159

### Random Value Generation

160

161

```typescript

162

import { randomBytes, randomHex, uuidV4 } from "web3-utils";

163

164

// Generate random bytes for cryptographic use

165

const entropy = randomBytes(32); // 32 bytes of entropy

166

console.log(entropy); // Uint8Array(32) [45, 123, 78, ...]

167

168

// Generate random hex for nonces, salts, etc.

169

const nonce = randomHex(8); // 8 bytes = 16 hex chars + "0x"

170

console.log(nonce); // "0x1a2b3c4d5e6f7890"

171

172

const salt = randomHex(16); // 16 bytes for salt

173

console.log(salt); // "0x1a2b3c4d5e6f78901a2b3c4d5e6f7890"

174

175

// Generate UUID for unique identifiers

176

const requestId = uuidV4();

177

console.log(requestId); // "123e4567-e89b-12d3-a456-426614174000"

178

179

const sessionId = uuidV4();

180

console.log(sessionId); // "987fcdeb-51d2-43a1-b456-426614174123"

181

```

182

183

### Cryptographic Applications

184

185

```typescript

186

import { randomBytes, randomHex } from "web3-utils";

187

188

// Generate private key (32 bytes)

189

function generatePrivateKey(): Uint8Array {

190

return randomBytes(32);

191

}

192

193

// Generate random IV for encryption

194

function generateIV(): Uint8Array {

195

return randomBytes(16); // 128-bit IV

196

}

197

198

// Generate random challenge for authentication

199

function generateChallenge(): string {

200

return randomHex(32); // 32 bytes challenge

201

}

202

203

// Generate random seed for deterministic operations

204

function generateSeed(): Uint8Array {

205

return randomBytes(64); // 512-bit seed

206

}

207

208

// Usage

209

const privateKey = generatePrivateKey();

210

const iv = generateIV();

211

const challenge = generateChallenge();

212

const seed = generateSeed();

213

214

console.log('Private key:', Array.from(privateKey, b => b.toString(16).padStart(2, '0')).join(''));

215

console.log('IV:', Array.from(iv, b => b.toString(16).padStart(2, '0')).join(''));

216

console.log('Challenge:', challenge);

217

console.log('Seed length:', seed.length);

218

```

219

220

### Data Validation

221

222

```typescript

223

import { isUint8Array, compareBlockNumbers, isContractInitOptions } from "web3-utils";

224

225

// Type checking for binary data

226

function processData(data: unknown) {

227

if (isUint8Array(data)) {

228

console.log('Processing binary data of length:', data.length);

229

// Safe to use Uint8Array methods

230

return data.slice(0, 10);

231

} else {

232

throw new Error('Expected Uint8Array');

233

}

234

}

235

236

// Block number comparison

237

function isNewerBlock(blockA: string | number, blockB: string | number): boolean {

238

return compareBlockNumbers(blockA, blockB) > 0;

239

}

240

241

// Usage examples

242

const buffer = Buffer.from([1, 2, 3, 4]);

243

const uint8 = new Uint8Array([5, 6, 7, 8]);

244

const array = [9, 10, 11, 12];

245

246

console.log(isUint8Array(buffer)); // true (Buffer extends Uint8Array)

247

console.log(isUint8Array(uint8)); // true

248

console.log(isUint8Array(array)); // false

249

250

// Block comparisons

251

console.log(compareBlockNumbers(100, 200)); // -1 (100 < 200)

252

console.log(compareBlockNumbers(200, 100)); // 1 (200 > 100)

253

console.log(compareBlockNumbers(150, 150)); // 0 (equal)

254

console.log(compareBlockNumbers('latest', 100)); // 1 ('latest' > any number)

255

console.log(compareBlockNumbers('pending', 'latest')); // 1 ('pending' > 'latest')

256

257

// Contract options validation

258

const options1 = { gasLimit: 21000, gasPrice: '20000000000' };

259

const options2 = { invalidOption: true };

260

261

if (isContractInitOptions(options1)) {

262

console.log('Valid contract options');

263

} else {

264

console.log('Invalid contract options');

265

}

266

```

267

268

### Security Best Practices

269

270

```typescript

271

import { randomBytes, randomHex, uuidV4 } from "web3-utils";

272

273

class SecurityUtils {

274

// Generate secure session token

275

static generateSessionToken(): string {

276

return randomHex(32); // 256-bit token

277

}

278

279

// Generate secure API key

280

static generateApiKey(): string {

281

const randomPart = randomHex(16);

282

const timestamp = Date.now().toString(16);

283

return `${randomPart.slice(2)}${timestamp}`; // Remove "0x" prefix

284

}

285

286

// Generate secure nonce for replay protection

287

static generateNonce(): string {

288

return randomBytes(8).reduce((acc, byte) => acc + byte.toString(16).padStart(2, '0'), '');

289

}

290

291

// Generate correlation ID for distributed tracing

292

static generateCorrelationId(): string {

293

return uuidV4();

294

}

295

296

// Generate secure random password

297

static generatePassword(length: number = 32): string {

298

const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';

299

const randomData = randomBytes(length);

300

301

return Array.from(randomData, byte => chars[byte % chars.length]).join('');

302

}

303

}

304

305

// Usage

306

const sessionToken = SecurityUtils.generateSessionToken();

307

const apiKey = SecurityUtils.generateApiKey();

308

const nonce = SecurityUtils.generateNonce();

309

const correlationId = SecurityUtils.generateCorrelationId();

310

const password = SecurityUtils.generatePassword(16);

311

312

console.log('Session token:', sessionToken);

313

console.log('API key:', apiKey);

314

console.log('Nonce:', nonce);

315

console.log('Correlation ID:', correlationId);

316

console.log('Password:', password);

317

```

318

319

### Random Data for Testing

320

321

```typescript

322

import { randomBytes, randomHex, uuidV4 } from "web3-utils";

323

324

class TestDataGenerator {

325

// Generate random Ethereum address format (not a real address)

326

static generateMockAddress(): string {

327

return '0x' + randomBytes(20).reduce((acc, byte) =>

328

acc + byte.toString(16).padStart(2, '0'), ''

329

);

330

}

331

332

// Generate random transaction hash format

333

static generateMockTxHash(): string {

334

return randomHex(32);

335

}

336

337

// Generate random block hash format

338

static generateMockBlockHash(): string {

339

return randomHex(32);

340

}

341

342

// Generate test data with random UUIDs

343

static generateTestRecord() {

344

return {

345

id: uuidV4(),

346

address: this.generateMockAddress(),

347

txHash: this.generateMockTxHash(),

348

blockHash: this.generateMockBlockHash(),

349

timestamp: Date.now(),

350

nonce: randomHex(4)

351

};

352

}

353

}

354

355

// Generate test data

356

const testRecords = Array.from({ length: 5 }, () =>

357

TestDataGenerator.generateTestRecord()

358

);

359

360

console.log('Test records:', testRecords);

361

```

362

363

## Migration Guide

364

365

For applications currently using the deprecated validation functions, migrate to the `web3-validator` package:

366

367

```typescript

368

// Old (deprecated)

369

import { isHex, isAddress } from "web3-utils";

370

371

// New (recommended)

372

import { isHex, isAddress } from "web3-validator";

373

374

// The API is the same, just import from web3-validator instead

375

const hexValue = "0x1234";

376

const address = "0x742E4C5b469F50A4a8b399D4915C1fc93d15651B";

377

378

console.log(isHex(hexValue)); // true

379

console.log(isAddress(address)); // true

380

```

381

382

## Types

383

384

```typescript { .api }

385

// Block number and tag types

386

type BlockNumberOrTag = number | bigint | string;

387

type BlockTags = 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';

388

389

// Contract initialization options

390

interface ContractInitOptions {

391

gasLimit?: number;

392

gasPrice?: string;

393

maxFeePerGas?: string;

394

maxPriorityFeePerGas?: string;

395

nonce?: number;

396

// ... other contract options

397

}

398

```