or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdindex.mdmemory-allocation.mdstring-encoding.mdxor-operations.md

xor-operations.mddocs/

0

# XOR Operations

1

2

Bitwise XOR operations and distance comparison functions for cryptographic applications, DHT (Distributed Hash Table) implementations, and Kademlia-style routing. These functions are essential for peer-to-peer networking and cryptographic protocols.

3

4

## Capabilities

5

6

### XOR Calculation

7

8

Performs bitwise XOR operation on two equal-length Uint8Arrays, returning a new array with the XOR result.

9

10

```typescript { .api }

11

/**

12

* Returns the xor distance between two Uint8Arrays

13

* @param a - First array for XOR operation

14

* @param b - Second array for XOR operation

15

* @returns New Uint8Array containing XOR result

16

* @throws Error if arrays have different lengths

17

*/

18

function xor(a: Uint8Array, b: Uint8Array): Uint8Array;

19

```

20

21

**Usage Examples:**

22

23

```typescript

24

import { xor } from "uint8arrays/xor";

25

26

// Basic XOR operation

27

const array1 = new Uint8Array([1, 0, 1, 0]);

28

const array2 = new Uint8Array([0, 1, 1, 1]);

29

const result = xor(array1, array2);

30

console.log(result); // Uint8Array(4) [1, 1, 0, 1]

31

32

// Cryptographic XOR (one-time pad)

33

const message = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"

34

const key = new Uint8Array([31, 42, 17, 5, 89]);

35

const encrypted = xor(message, key);

36

const decrypted = xor(encrypted, key); // XOR with same key to decrypt

37

console.log(decrypted); // [72, 101, 108, 108, 111] - original message

38

39

// DHT node distance calculation

40

const nodeId1 = new Uint8Array([0x12, 0x34, 0x56, 0x78]);

41

const nodeId2 = new Uint8Array([0x9A, 0xBC, 0xDE, 0xF0]);

42

const distance = xor(nodeId1, nodeId2);

43

console.log(distance); // Uint8Array showing XOR distance

44

45

// Binary operations

46

const bits1 = new Uint8Array([0b10101010]);

47

const bits2 = new Uint8Array([0b11110000]);

48

const xorBits = xor(bits1, bits2);

49

console.log(xorBits[0].toString(2)); // "1011010" (binary result)

50

```

51

52

### XOR Distance Comparison

53

54

Compares XOR distances for DHT and Kademlia applications. Determines which of two XOR results represents a smaller distance.

55

56

```typescript { .api }

57

/**

58

* Compares two Uint8Arrays representing two xor distances. Returns -1 if a

59

* is a lower distance, 1 if b is a lower distance or 0 if the distances

60

* are equal.

61

* @param a - First XOR distance to compare

62

* @param b - Second XOR distance to compare

63

* @returns -1 if a is closer, 1 if b is closer, 0 if equal

64

* @throws Error if arrays have different lengths

65

*/

66

function xorCompare(a: Uint8Array, b: Uint8Array): -1 | 0 | 1;

67

```

68

69

**Usage Examples:**

70

71

```typescript

72

import { xor, xorCompare } from "uint8arrays";

73

74

// DHT routing example

75

const target = new Uint8Array([0xFF, 0xFF, 0x00, 0x00]);

76

const node1 = new Uint8Array([0xFF, 0xFE, 0x01, 0x23]);

77

const node2 = new Uint8Array([0xFF, 0xFC, 0x45, 0x67]);

78

79

// Calculate distances to target

80

const distance1 = xor(target, node1);

81

const distance2 = xor(target, node2);

82

83

// Compare which node is closer to target

84

const comparison = xorCompare(distance1, distance2);

85

console.log(comparison); // -1 (node1 is closer), 1 (node2 is closer), or 0 (equal)

86

87

// Kademlia k-bucket sorting

88

const targetKey = new Uint8Array([0x12, 0x34, 0x56, 0x78]);

89

const peers = [

90

new Uint8Array([0x11, 0x22, 0x33, 0x44]),

91

new Uint8Array([0x99, 0xAA, 0xBB, 0xCC]),

92

new Uint8Array([0x13, 0x35, 0x57, 0x79])

93

];

94

95

// Sort peers by distance to target

96

const sortedPeers = peers.sort((a, b) => {

97

const distanceA = xor(targetKey, a);

98

const distanceB = xor(targetKey, b);

99

return xorCompare(distanceA, distanceB);

100

});

101

102

console.log("Peers sorted by distance to target:", sortedPeers);

103

104

// Equal distance detection

105

const equalDist1 = new Uint8Array([0x01, 0x02, 0x03]);

106

const equalDist2 = new Uint8Array([0x01, 0x02, 0x03]);

107

console.log(xorCompare(equalDist1, equalDist2)); // 0 (equal distances)

108

```

109

110

## DHT and P2P Applications

111

112

### Kademlia Routing Table

113

114

```typescript

115

import { xor, xorCompare } from "uint8arrays";

116

117

class KademliaNode {

118

constructor(public id: Uint8Array) {}

119

120

findClosestPeers(targetId: Uint8Array, peers: Uint8Array[], k: number = 20): Uint8Array[] {

121

return peers

122

.map(peerId => ({

123

id: peerId,

124

distance: xor(targetId, peerId)

125

}))

126

.sort((a, b) => xorCompare(a.distance, b.distance))

127

.slice(0, k)

128

.map(peer => peer.id);

129

}

130

131

shouldReplaceInBucket(targetId: Uint8Array, currentPeer: Uint8Array, candidatePeer: Uint8Array): boolean {

132

const currentDistance = xor(targetId, currentPeer);

133

const candidateDistance = xor(targetId, candidatePeer);

134

return xorCompare(candidateDistance, currentDistance) === -1; // candidate is closer

135

}

136

}

137

```

138

139

### Content Addressing

140

141

```typescript

142

import { xor, xorCompare, fromString } from "uint8arrays";

143

144

// Find nodes responsible for storing content

145

function findStorageNodes(contentHash: string, availableNodes: string[]): string[] {

146

const contentId = fromString(contentHash, "hex");

147

const nodeDistances = availableNodes.map(nodeIdHex => {

148

const nodeId = fromString(nodeIdHex, "hex");

149

return {

150

nodeId: nodeIdHex,

151

distance: xor(contentId, nodeId)

152

};

153

});

154

155

// Sort by XOR distance and take closest nodes

156

return nodeDistances

157

.sort((a, b) => xorCompare(a.distance, b.distance))

158

.slice(0, 3) // Store on 3 closest nodes

159

.map(node => node.nodeId);

160

}

161

```

162

163

## Cryptographic Applications

164

165

### One-Time Pad Encryption

166

167

```typescript

168

import { xor, fromString, toString } from "uint8arrays";

169

170

function encryptMessage(message: string, key: Uint8Array): Uint8Array {

171

const messageBytes = fromString(message, "utf8");

172

if (messageBytes.length > key.length) {

173

throw new Error("Key must be at least as long as message");

174

}

175

return xor(messageBytes, key.slice(0, messageBytes.length));

176

}

177

178

function decryptMessage(encrypted: Uint8Array, key: Uint8Array): string {

179

const decrypted = xor(encrypted, key.slice(0, encrypted.length));

180

return toString(decrypted, "utf8");

181

}

182

183

// Usage

184

const key = new Uint8Array(256).map(() => Math.floor(Math.random() * 256));

185

const message = "Secret message";

186

const encrypted = encryptMessage(message, key);

187

const decrypted = decryptMessage(encrypted, key);

188

console.log(decrypted); // "Secret message"

189

```

190

191

### Stream Cipher Operations

192

193

```typescript

194

import { xor } from "uint8arrays/xor";

195

196

function streamCipherXOR(data: Uint8Array, keystream: Uint8Array): Uint8Array {

197

if (data.length !== keystream.length) {

198

throw new Error("Data and keystream must be same length");

199

}

200

return xor(data, keystream);

201

}

202

203

// Generate keystream (simplified example)

204

function generateKeystream(length: number, seed: number): Uint8Array {

205

const keystream = new Uint8Array(length);

206

let state = seed;

207

for (let i = 0; i < length; i++) {

208

state = (state * 1103515245 + 12345) & 0x7FFFFFFF;

209

keystream[i] = (state >> 16) & 0xFF;

210

}

211

return keystream;

212

}

213

```

214

215

## Performance Characteristics

216

217

### xor()

218

- **Time Complexity**: O(n) where n is array length

219

- **Space Complexity**: O(n) for result array

220

- **Memory Access**: Sequential, cache-friendly

221

- **Optimization**: Uses native bitwise operations

222

223

### xorCompare()

224

- **Time Complexity**: O(n) worst case, O(1) best case

225

- **Early Termination**: Stops at first differing byte

226

- **Byte Order**: Compares from most significant to least significant byte

227

- **Deterministic**: Always returns consistent ordering

228

229

## Error Handling

230

231

Both functions validate input parameters:

232

233

```typescript

234

// Length mismatch errors

235

try {

236

xor(new Uint8Array([1, 2]), new Uint8Array([1, 2, 3]));

237

} catch (error) {

238

console.log(error.message); // "Inputs should have the same length"

239

}

240

241

try {

242

xorCompare(new Uint8Array([1]), new Uint8Array([1, 2]));

243

} catch (error) {

244

console.log(error.message); // "Inputs should have the same length"

245

}

246

```

247

248

## Security Considerations

249

250

- **XOR Properties**: A ⊕ A = 0, A ⊕ 0 = A, A ⊕ B = B ⊕ A

251

- **Key Reuse**: Never reuse keys in cryptographic XOR operations

252

- **Perfect Secrecy**: XOR with truly random key provides perfect secrecy

253

- **Distance Metrics**: XOR distance satisfies triangle inequality for DHT applications