-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add pegout transaction created event assertions
- Loading branch information
1 parent
36dbb1e
commit 13ea2e4
Showing
3 changed files
with
95 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
class VarInt { | ||
constructor(value) { | ||
if (typeof value === 'number' || typeof value === 'bigint') { | ||
this.value = BigInt(value); | ||
this.originallyEncodedSize = this.getSizeInBytes(); | ||
} else if (Buffer.isBuffer(value)) { | ||
this.value = this.decode(value); | ||
this.originallyEncodedSize = this.getSizeInBytes(); | ||
} else { | ||
throw new Error('Invalid input: value should be a number or buffer'); | ||
} | ||
} | ||
|
||
getOriginalSizeInBytes() { | ||
return this.originallyEncodedSize; | ||
} | ||
|
||
getSizeInBytes() { | ||
return VarInt.sizeOf(this.value); | ||
} | ||
|
||
static sizeOf(value) { | ||
if (value < 0) return 9; | ||
if (value < 253) return 1; | ||
if (value <= 0xFFFF) return 3; | ||
if (value <= 0xFFFFFFFF) return 5; | ||
return 9; | ||
} | ||
|
||
encode() { | ||
let bytes; | ||
switch (this.getSizeInBytes()) { | ||
case 1: | ||
return Buffer.from([Number(this.value)]); | ||
case 3: | ||
return Buffer.from([253, Number(this.value & 0xFF), Number((this.value >> 8) & 0xFF)]); | ||
case 5: | ||
bytes = Buffer.alloc(5); | ||
bytes[0] = 254; | ||
bytes.writeUInt32LE(Number(this.value), 1); | ||
return bytes; | ||
case 9: | ||
bytes = Buffer.alloc(9); | ||
bytes[0] = 255; | ||
bytes.writeBigUInt64LE(this.value, 1); | ||
return bytes; | ||
default: | ||
throw new Error('Invalid size for encoding'); | ||
} | ||
} | ||
|
||
decode(buffer) { | ||
const first = buffer[0]; | ||
if (first < 253) { | ||
return BigInt(first); | ||
} else if (first === 253) { | ||
return BigInt(buffer.readUInt16LE(1)); | ||
} else if (first === 254) { | ||
return BigInt(buffer.readUInt32LE(1)); | ||
} else { | ||
return buffer.readBigUInt64LE(1); | ||
} | ||
} | ||
} | ||
|
||
module.exports = { VarInt }; |