UNPKG

1.29 kBJavaScriptView Raw
1/**
2 * VarInt (a.k.a. Compact Size)
3 * ============================
4 *
5 * A varInt is a varible sized integer, and it is a format that is unique to
6 * bitcoin, and used throughout bitcoin to represent the length of binary data
7 * in a compact format that can take up as little as 1 byte or as much as 9
8 * bytes.
9 */
10'use strict'
11
12import { Br } from './br'
13import { Bw } from './bw'
14import { Struct } from './struct'
15
16class VarInt extends Struct {
17 constructor (buf) {
18 super({ buf })
19 }
20
21 fromJSON (json) {
22 this.fromObject({
23 buf: Buffer.from(json, 'hex')
24 })
25 return this
26 }
27
28 toJSON () {
29 return this.buf.toString('hex')
30 }
31
32 fromBuffer (buf) {
33 this.buf = buf
34 return this
35 }
36
37 fromBr (br) {
38 this.buf = br.readVarIntBuf()
39 return this
40 }
41
42 fromBn (bn) {
43 this.buf = new Bw().writeVarIntBn(bn).toBuffer()
44 return this
45 }
46
47 static fromBn (bn) {
48 return new this().fromBn(bn)
49 }
50
51 fromNumber (num) {
52 this.buf = new Bw().writeVarIntNum(num).toBuffer()
53 return this
54 }
55
56 static fromNumber (num) {
57 return new this().fromNumber(num)
58 }
59
60 toBuffer () {
61 return this.buf
62 }
63
64 toBn () {
65 return new Br(this.buf).readVarIntBn()
66 }
67
68 toNumber () {
69 return new Br(this.buf).readVarIntNum()
70 }
71}
72
73export { VarInt }