All files / src/serializer decoder.ts

94.67% Statements 231/244
89.33% Branches 134/150
100% Functions 21/21
94.6% Lines 228/241

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480                                                                                                      1x       14x   122x 2x   120x       14x 14x 14x 14x                   339x 339x 339x   339x 19x   320x   320x 25x 25x 25x 25x 1x     295x   319x 319x 319x   1x           338x 338x 295x     338x           338x 338x   69x     69x 69x 69x   69x 2x   69x 269x 258x 11x 11x         14x                     1x     962x 3x   959x 12x 11x 11x           948x 15x 8x     940x 121x 121x 121x 216x 216x 215x   120x   819x     1035x 1035x 667x   368x   91x 91x 11x 11x 277x 249x 249x     249x 249x 776x 776x 755x   228x 215x 215x   13x   28x 27x 27x 27x 1x   26x 26x 26x 26x 24x   2x   1x     1x                 2582x 124x 91x   33x 31x 31x         2x 2458x 376x 1x   375x 375x 375x 390x 390x 389x   374x   2082x     2472x 2472x   1x 2471x 578x     578x 91x   487x 487x     487x 487x 2238x 2238x 2234x   483x 478x 478x   5x   1893x   76x 34x 34x 42x 1x 1x   41x   301x 76x 2x   74x 74x 74x 74x 74x 73x 73x   1x     1817x   71x 71x       1746x                     60x 5x   55x 2x   53x 53x 40x   13x 1x   12x 12x 6x 6x 12x 12x 11x   5x 2x 2x   3x   6x 4x 4x 3x 3x   1x   2x 2x 2x 2x 2x           1x   69x         69x   69x 69x 69x       1398x       1383x 1x         2x     2x       4x       6x 6x         543x 543x         5x   5x   1x 1x   4x 4x       5x 5x       469x 469x 469x 477x 477x 477x 477x 469x     469x       1x 1x     1x         829x 828x 828x 828x       191x 191x      
/**
 * Antelope/EOSIO ABI Decoder
 */
 
import {ABI, ABIDef, Bytes, BytesType, Variant} from '../chain'
 
import {
    ABISerializable,
    ABISerializableConstructor,
    ABISerializableType,
    abiTypeString,
    synthesizeABI,
    toTypeDescriptor,
} from './serializable'
 
import {buildTypeLookup, BuiltinTypes, getTypeName, TypeLookup} from './builtins'
 
import {isInstanceOf} from '../utils'
 
interface DecodeArgsBase {
    abi?: ABIDef
    data?: BytesType | ABIDecoder
    json?: string
    object?: any
    customTypes?: ABISerializableConstructor[]
    /** Optional encoder metadata. */
    metadata?: Record<string, any>
    /**
     * Binary extension handling, if set to true missing extensions will be initialized,
     * otherwise they will be set to null. Defaults to false.
     */
    strictExtensions?: boolean
    /**
     * Set to ignore invalid UTF-8, otherwise an error will be thrown (default).
     */
    ignoreInvalidUTF8?: boolean
}
 
interface TypedDecodeArgs<T extends ABISerializableType> extends DecodeArgsBase {
    type: T
}
 
interface BuiltinDecodeArgs<T extends keyof BuiltinTypes> extends DecodeArgsBase {
    type: T
}
 
interface UntypedDecodeArgs extends DecodeArgsBase {
    type: ABISerializableType
}
 
class DecodingError extends Error {
    static __className = 'DecodingError'
    ctx: DecodingContext
    underlyingError: Error
    constructor(ctx: DecodingContext, underlyingError: Error) {
        const path = ctx.codingPath
            .map(({field, type}) => {
                if (typeof field === 'number') {
                    return field
                } else {
                    return `${field}<${type.typeName}>`
                }
            })
            .join('.')
        super(`Decoding error at ${path}: ${underlyingError.message}`)
        this.stack = underlyingError.stack
        this.ctx = ctx
        this.underlyingError = underlyingError
    }
}
 
export function abiDecode<T extends keyof BuiltinTypes>(args: BuiltinDecodeArgs<T>): BuiltinTypes[T]
export function abiDecode<T extends ABISerializableConstructor>(
    args: TypedDecodeArgs<T>
): InstanceType<T>
export function abiDecode(args: UntypedDecodeArgs): ABISerializable
export function abiDecode(args: UntypedDecodeArgs | BuiltinDecodeArgs<any> | TypedDecodeArgs<any>) {
    const descriptor = toTypeDescriptor(args.type)
    const typeName = abiTypeString(descriptor)
    const customTypes = args.customTypes || []
    let abi: ABI
    if (args.abi) {
        abi = ABI.from(args.abi)
    } else {
        try {
            let type: ABISerializableConstructor
            if (typeof descriptor.type === 'string') {
                const lookup = buildTypeLookup(customTypes)
                const rName = new ABI.ResolvedType(descriptor.type).name // type name w/o suffixes
                type = lookup[rName] as ABISerializableConstructor
                if (!type) {
                    throw new Error(`Unknown type: ${descriptor.type}`)
                }
            } else {
                type = descriptor.type
            }
            const synthesized = synthesizeABI(type)
            abi = synthesized.abi
            customTypes.push(...synthesized.types)
        } catch (error) {
            throw Error(
                `Unable to synthesize ABI for: ${typeName} (${error.message}). ` +
                    'To decode non-class types you need to pass the ABI definition manually.'
            )
        }
    }
    const resolved = abi.resolveType(typeName)
    if (typeof descriptor.type !== 'string') {
        customTypes.unshift(descriptor.type)
    }
 
    const ctx: DecodingContext = {
        types: buildTypeLookup(customTypes),
        strictExtensions: args.strictExtensions || false,
        codingPath: [{field: 'root', type: resolved}],
    }
 
    try {
        if (args.data || args.data === '') {
            let decoder: ABIDecoder
            Iif (isInstanceOf(args.data, ABIDecoder)) {
                decoder = args.data
            } else {
                const bytes = Bytes.from(args.data)
                const fatal = args.ignoreInvalidUTF8 === undefined ? true : !args.ignoreInvalidUTF8
                decoder = new ABIDecoder(bytes.array, new TextDecoder('utf-8', {fatal}))
            }
            if (args.metadata) {
                decoder.metadata = args.metadata
            }
            return decodeBinary(resolved, decoder, ctx)
        } else if (args.object !== undefined) {
            return decodeObject(args.object, resolved, ctx)
        } else Eif (args.json) {
            return decodeObject(JSON.parse(args.json), resolved, ctx)
        } else {
            throw new Error('Nothing to decode, you must set one of data, json, object')
        }
    } catch (error) {
        throw new DecodingError(ctx, error)
    }
}
 
interface DecodingContext {
    types: TypeLookup
    strictExtensions: boolean
    codingPath: {field: string | number; type: ABI.ResolvedType}[]
}
 
/** Marker for objects when they have been resolved, i.e. their types `from` factory method will not need to resolve children. */
export const Resolved = Symbol('Resolved')
 
function decodeBinary(type: ABI.ResolvedType, decoder: ABIDecoder, ctx: DecodingContext): any {
    if (ctx.codingPath.length > 32) {
        throw new Error('Maximum decoding depth exceeded')
    }
    if (type.isExtension) {
        if (!decoder.canRead()) {
            Eif (ctx.strictExtensions) {
                return defaultValue(type, ctx)
            } else {
                return null
            }
        }
    }
    if (type.isOptional) {
        if (decoder.readByte() === 0) {
            return null
        }
    }
    if (type.isArray) {
        const len = decoder.readVaruint32()
        const rv: any[] = []
        for (let i = 0; i < len; i++) {
            ctx.codingPath.push({field: i, type})
            rv.push(decodeInner())
            ctx.codingPath.pop()
        }
        return rv
    } else {
        return decodeInner()
    }
    function decodeInner() {
        const abiType = ctx.types[type.name]
        if (abiType && abiType.fromABI) {
            return abiType.fromABI(decoder)
        } else {
            if (type.ref) {
                // follow type alias
                ctx.codingPath.push({field: '', type: type.ref})
                const rv = decodeBinary(type.ref, decoder, ctx)
                ctx.codingPath.pop()
                return rv
            } else if (type.fields) {
                const fields = type.allFields
                Iif (!fields) {
                    throw new Error('Invalid struct fields')
                }
                const rv: any = {}
                for (const field of fields) {
                    ctx.codingPath.push({field: field.name, type: field.type})
                    rv[field.name] = decodeBinary(field.type, decoder, ctx)
                    ctx.codingPath.pop()
                }
                if (abiType) {
                    rv[Resolved] = true
                    return abiType.from(rv)
                } else {
                    return rv
                }
            } else if (type.variant) {
                const vIdx = decoder.readByte()
                const vType = type.variant[vIdx]
                if (!vType) {
                    throw new Error(`Unknown variant idx: ${vIdx}`)
                }
                ctx.codingPath.push({field: `v${vIdx}`, type: vType})
                const rv = [vType.typeName, decodeBinary(vType, decoder, ctx)]
                ctx.codingPath.pop()
                if (abiType) {
                    return abiType.from(rv)
                } else {
                    return rv
                }
            } else Iif (abiType) {
                throw new Error('Invalid type')
            } else {
                throw new Error(
                    type.name === 'any' ? "Unable to decode 'any' type from binary" : 'Unknown type'
                )
            }
        }
    }
}
 
function decodeObject(value: any, type: ABI.ResolvedType, ctx: DecodingContext): any {
    if (value === null || value === undefined) {
        if (type.isOptional) {
            return null
        }
        if (type.isExtension) {
            Eif (ctx.strictExtensions) {
                return defaultValue(type, ctx)
            } else {
                return null
            }
        }
        throw new Error(`Unexpectedly encountered ${value} for non-optional`)
    } else if (type.isArray) {
        if (!Array.isArray(value)) {
            throw new Error('Expected array')
        }
        const rv: any[] = []
        const len = value.length
        for (let i = 0; i < len; i++) {
            ctx.codingPath.push({field: i, type})
            rv.push(decodeInner(value[i]))
            ctx.codingPath.pop()
        }
        return rv
    } else {
        return decodeInner(value)
    }
    function decodeInner(value: any) {
        const abiType = ctx.types[type.name]
        if (type.ref && !abiType) {
            // follow type alias
            return decodeObject(value, type.ref, ctx)
        } else if (type.fields) {
            Iif (typeof value !== 'object') {
                throw new Error('Expected object')
            }
            if (typeof abiType === 'function' && isInstanceOf(value, abiType)) {
                return value
            }
            const fields = type.allFields
            Iif (!fields) {
                throw new Error('Invalid struct fields')
            }
            const struct: any = {}
            for (const field of fields) {
                ctx.codingPath.push({field: field.name, type: field.type})
                struct[field.name] = decodeObject(value[field.name], field.type, ctx)
                ctx.codingPath.pop()
            }
            if (abiType) {
                struct[Resolved] = true
                return abiType.from(struct)
            } else {
                return struct
            }
        } else if (type.variant) {
            let vName: string | undefined
            if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'string') {
                vName = value[0]
                value = value[1]
            } else if (isInstanceOf(value, Variant)) {
                vName = value.variantName
                value = value.value
            } else {
                vName = getTypeName(value)
            }
            const vIdx = type.variant.findIndex((t) => t.typeName === vName)
            if (vIdx === -1) {
                throw new Error(`Unknown variant type: ${vName}`)
            }
            const vType = type.variant[vIdx]
            ctx.codingPath.push({field: `v${vIdx}`, type: vType})
            const rv = [vType.typeName, decodeObject(value, vType, ctx)]
            ctx.codingPath.pop()
            if (abiType) {
                rv[Resolved] = true
                return abiType.from(rv)
            } else {
                return rv
            }
        } else {
            if (!abiType) {
                // special case for `any` when decoding from object
                Eif (type.name === 'any') {
                    return value
                }
                throw new Error('Unknown type')
            }
            return abiType.from(value)
        }
    }
}
 
/** Return default value (aka initialized value, matching C++ where possible) for given type */
function defaultValue(
    type: ABI.ResolvedType,
    ctx: DecodingContext,
    seen: Set<string> = new Set()
): any {
    if (type.isArray) {
        return []
    }
    if (type.isOptional) {
        return null
    }
    const abiType = ctx.types[type.name]
    if (abiType && abiType.abiDefault) {
        return abiType.abiDefault()
    }
    if (seen.has(type.name)) {
        throw new Error('Circular type reference')
    }
    seen.add(type.name)
    if (type.allFields) {
        const rv: any = {}
        for (const field of type.allFields) {
            ctx.codingPath.push({field: field.name, type: field.type})
            rv[field.name] = defaultValue(field.type, ctx, seen)
            ctx.codingPath.pop()
        }
        if (abiType) {
            rv[Resolved] = true
            return abiType.from(rv)
        }
        return rv
    }
    if (type.variant && type.variant.length > 0) {
        const rv = [type.variant[0].typeName, defaultValue(type.variant[0], ctx)]
        if (abiType) {
            rv[Resolved] = true
            return abiType.from(rv)
        }
        return rv
    }
    Eif (type.ref) {
        ctx.codingPath.push({field: '', type: type.ref})
        const rv = defaultValue(type.ref, ctx, seen)
        ctx.codingPath.pop()
        return rv
    }
    throw new Error('Unable to determine default value')
}
 
export class ABIDecoder {
    static __className = 'ABIDecoder'
 
    private pos = 0
    private data: DataView
    private textDecoder: TextDecoder
 
    /** User declared metadata, can be used to pass info to instances when decoding.  */
    metadata: Record<string, any> = {}
 
    constructor(private array: Uint8Array, textDecoder?: TextDecoder) {
        this.textDecoder = textDecoder || new TextDecoder('utf-8', {fatal: true})
        this.data = new DataView(array.buffer, array.byteOffset, array.byteLength)
    }
 
    canRead(bytes = 1): boolean {
        return !(this.pos + bytes > this.array.byteLength)
    }
 
    private ensure(bytes: number) {
        if (!this.canRead(bytes)) {
            throw new Error('Read past end of buffer')
        }
    }
 
    setPosition(pos: number) {
        Iif (pos < 0 || pos > this.array.byteLength) {
            throw new Error('Invalid position')
        }
        this.pos = pos
    }
 
    getPosition(): number {
        return this.pos
    }
 
    advance(bytes: number) {
        this.ensure(bytes)
        this.pos += bytes
    }
 
    /** Read one byte. */
    readByte(): number {
        this.ensure(1)
        return this.array[this.pos++]
    }
 
    /** Read floating point as JavaScript number, 32 or 64 bits. */
    readFloat(byteWidth: number) {
        this.ensure(byteWidth)
        let rv: number
        switch (byteWidth) {
            case 4:
                rv = this.data.getFloat32(this.pos, true)
                break
            case 8:
                rv = this.data.getFloat64(this.pos, true)
                break
            default:
                throw new Error('Invalid float size')
        }
        this.pos += byteWidth
        return rv
    }
 
    readVaruint32() {
        let v = 0
        let bit = 0
        for (;;) {
            const b = this.readByte()
            v |= (b & 0x7f) << bit
            bit += 7
            if (!(b & 0x80)) {
                break
            }
        }
        return v >>> 0
    }
 
    readVarint32() {
        const v = this.readVaruint32()
        Iif (v & 1) {
            return (~v >> 1) | 0x8000_0000
        } else {
            return v >>> 1
        }
    }
 
    readArray(length: number) {
        this.ensure(length)
        const rv = this.array.subarray(this.pos, this.pos + length)
        this.pos += length
        return rv
    }
 
    readString() {
        const length = this.readVaruint32()
        return this.textDecoder.decode(this.readArray(length))
    }
}