/
index.js
226 lines (183 loc) · 4.99 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/**
* @module amino.encode
*/
import vstruct from "varstruct"
import { Buffer } from "safe-buffer"
import is from "is_js"
import { UVarInt } from "./varint"
import typeToTyp3 from "../utils/encoderHelper"
import { typePrefix } from "../tx/"
const VarString = vstruct.VarString(UVarInt)
const sortObject = obj => {
if (obj === null) return null
if (typeof obj !== "object") return obj
// arrays have typeof "object" in js!
if (Array.isArray(obj))
return obj.map(sortObject)
const sortedKeys = Object.keys(obj).sort()
const result = {}
sortedKeys.forEach(key => {
result[key] = sortObject(obj[key])
})
return result
}
/**
* encode number
* @param num
*/
export const encodeNumber = (num) => UVarInt.encode(num)
/**
* encode bool
* @param b
*/
export const encodeBool = (b) => b ? UVarInt.encode(1): UVarInt.encode(0)
/**
* encode string
* @param str
*/
export const encodeString = (str) => VarString.encode(str)
/**
* encode time
* @param value
*/
export const encodeTime = (value) => {
const millis = new Date(value).getTime()
const seconds = Math.floor(millis / 1000)
const nanos = Number(seconds.toString().padEnd(9, "0"))
const buffer = Buffer.alloc(14)
buffer[0] = (1 << 3) | 1 // field 1, typ3 1
buffer.writeUInt32LE(seconds, 1)
buffer[9] = (2 << 3) | 5 // field 2, typ3 5
buffer.writeUInt32LE(nanos, 10)
return buffer
}
/**
* @param obj -- {object}
* @return bytes {Buffer}
*/
export const convertObjectToSignBytes = obj =>
Buffer.from(JSON.stringify(sortObject(obj)))
/**
* js amino MarshalBinary
* @param {Object} obj
* */
export const marshalBinary = (obj) => {
if (!is.object(obj))
throw new TypeError("data must be an object")
return encodeBinary(obj, -1, true).toString("hex")
}
/**
* js amino MarshalBinaryBare
* @param {Object} obj
* */
export const marshalBinaryBare = (obj) => {
if (!is.object(obj))
throw new TypeError("data must be an object")
return encodeBinary(obj).toString("hex")
}
/**
* This is the main entrypoint for encoding all types in binary form.
* @param {*} js data type (not null, not undefined)
* @param {Number} field index of object
* @param {Boolean} isByteLenPrefix
* @return {Buffer} binary of object.
*/
export const encodeBinary = (val, fieldNum, isByteLenPrefix) => {
if (val === null || val === undefined)
throw new TypeError("unsupported type")
if(Buffer.isBuffer(val)) {
if(isByteLenPrefix) {
return Buffer.concat([UVarInt.encode(val.length), val])
}
return val
}
if(is.array(val)) {
return encodeArrayBinary(fieldNum, val, isByteLenPrefix)
}
if(is.number(val)) {
return encodeNumber(val)
}
if(is.boolean(val)) {
return encodeBool(val)
}
if(is.string(val)) {
return encodeString(val)
}
if(is.object(val)) {
return encodeObjectBinary(val, isByteLenPrefix)
}
return
}
/**
* prefixed with bytes length
* @param {Buffer} bytes
* @return {Buffer} with bytes length prefixed
*/
export const encodeBinaryByteArray = (bytes) => {
const lenPrefix = bytes.length
return Buffer.concat([UVarInt.encode(lenPrefix), bytes])
}
/**
*
* @param {Object} obj
* @return {Buffer} with bytes length prefixed
*/
export const encodeObjectBinary = (obj, isByteLenPrefix) => {
const bufferArr = []
Object.keys(obj).forEach((key, index) => {
if (key === "msgType" || key === "version") return
if (isDefaultValue(obj[key])) return
if (is.array(obj[key]) && obj[key].length > 0) {
bufferArr.push(encodeArrayBinary(index, obj[key]))
} else {
bufferArr.push(encodeTypeAndField(index, obj[key]))
bufferArr.push(encodeBinary(obj[key], index, true))
}
})
let bytes = Buffer.concat(bufferArr)
// add prefix
if(typePrefix[obj.msgType]) {
const prefix = Buffer.from(typePrefix[obj.msgType], "hex")
bytes = Buffer.concat([prefix, bytes])
}
// Write byte-length prefixed.
if(isByteLenPrefix) {
const lenBytes = UVarInt.encode(bytes.length)
bytes = Buffer.concat([lenBytes, bytes])
}
return bytes
}
/**
* @param {Number} fieldNum object field index
* @param {Array} arr
* @param {Boolean} isByteLenPrefix
* @return {Buffer} bytes of array
*/
export const encodeArrayBinary = (fieldNum, arr, isByteLenPrefix) => {
const result = []
arr.forEach((item) => {
result.push(encodeTypeAndField(fieldNum, item))
if (isDefaultValue(item)) {
result.push(Buffer.from("00", "hex"))
return
}
result.push(encodeBinary(item, fieldNum, true))
})
//encode length
if(isByteLenPrefix){
const length = result.reduce((prev, item) => (prev + item.length), 0)
result.unshift(UVarInt.encode(length))
}
return Buffer.concat(result)
}
// Write field key.
const encodeTypeAndField = (index, field) => {
const value = (index + 1) << 3 | typeToTyp3(field)
return UVarInt.encode(value)
}
const isDefaultValue = (obj) => {
if(obj === null) return false
return (is.number(obj) && obj === 0)
|| (is.string(obj) && obj === "")
|| (is.array(obj) && obj.length === 0)
}