Use compact* from util for encoding (#409)

* Use compact* from util for encoding

* Remove @polkadot/extrinsics from types imports

* Cleanup manual length concat

* Add missing @polkadot/types dependencies
This commit is contained in:
Jaco Greeff
2018-11-21 17:21:44 +01:00
committed by GitHub
parent 44ad29021b
commit d0ff8937a4
26 changed files with 103 additions and 163 deletions
+5 -8
View File
@@ -2,10 +2,10 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a, isHex, isString, isU8a, u8aConcat, u8aToU8a } from '@polkadot/util';
import { hexToU8a, isHex, isString, isU8a, u8aToU8a } from '@polkadot/util';
import { AnyU8a } from './types';
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
import Compact from './codec/Compact';
import U8a from './codec/U8a';
// A Bytes wrapper for Vec<u8>. The significant difference between this and a normal Uint8Array
@@ -30,7 +30,7 @@ export default class Bytes extends U8a {
// i.e. new Bytes(new Bytes(...)) will work as expected
return value;
} else if (isU8a(value)) {
const [offset, length] = Compact.decodeU8a(value, DEFAULT_LENGTH_BITS);
const [offset, length] = Compact.decodeU8a(value);
return value.subarray(offset, offset + length.toNumber());
} else if (Array.isArray(value) || isString(value)) {
@@ -41,15 +41,12 @@ export default class Bytes extends U8a {
}
get encodedLength (): number {
return this.length + Compact.encodeU8a(this.length, DEFAULT_LENGTH_BITS).length;
return this.length + Compact.encodeU8a(this.length).length;
}
toU8a (isBare?: boolean): Uint8Array {
return isBare
? super.toU8a(isBare)
: u8aConcat(
Compact.encodeU8a(this.length, DEFAULT_LENGTH_BITS),
this
);
: Compact.addLengthPrefix(this);
}
}
+6 -12
View File
@@ -5,10 +5,10 @@
import { KeyringPair } from '@polkadot/keyring/types';
import { AnyNumber, AnyU8a, Codec } from './types';
import { hexToU8a, isHex, isU8a, u8aConcat, u8aToHex } from '@polkadot/util';
import { hexToU8a, isHex, isU8a, u8aToHex } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
import Compact from './codec/Compact';
import Struct from './codec/Struct';
import ExtrinsicSignature from './ExtrinsicSignature';
import Hash from './Hash';
@@ -49,13 +49,10 @@ export default class Extrinsic extends Struct {
const u8a = hexToU8a(value);
return Extrinsic.decodeExtrinsic(
u8aConcat(
Compact.encodeU8a(u8a.length, DEFAULT_LENGTH_BITS),
u8a
)
Compact.addLengthPrefix(u8a)
);
} else if (isU8a(value)) {
const [offset, length] = Compact.decodeU8a(value, DEFAULT_LENGTH_BITS);
const [offset, length] = Compact.decodeU8a(value);
return value.subarray(offset, offset + length.toNumber());
}
@@ -107,7 +104,7 @@ export default class Extrinsic extends Struct {
get encodedLength (): number {
const length = this.length;
return length + Compact.encodeU8a(length, DEFAULT_LENGTH_BITS).length;
return length + Compact.encodeU8a(length).length;
}
sign (signerPair: KeyringPair, nonce: AnyNumber, blockHash: AnyU8a): Extrinsic {
@@ -121,10 +118,7 @@ export default class Extrinsic extends Struct {
return isBare
? encoded
: u8aConcat(
Compact.encodeU8a(encoded.length, DEFAULT_LENGTH_BITS),
encoded
);
: Compact.addLengthPrefix(encoded);
}
toHex (): string {
+2 -2
View File
@@ -6,7 +6,7 @@ import { AnyNumber } from './types';
import { hexToU8a, isHex, isU8a } from '@polkadot/util';
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
import Compact from './codec/Compact';
import Enum from './codec/Enum';
import EnumType from './codec/EnumType';
import Option from './codec/Option';
@@ -337,7 +337,7 @@ export default class RuntimeMetadata extends Struct {
// is properly encoded. Here we pull the prefix, check it agianst the length -
// if matches, then we have the length, otherwise we assume it is an older node
// and use the whole buffer
const [offset, length] = Compact.decodeU8a(value, DEFAULT_LENGTH_BITS);
const [offset, length] = Compact.decodeU8a(value);
return value.length === (offset + length.toNumber())
? value.subarray(offset)
+21 -3
View File
@@ -2,14 +2,15 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ExtrinsicFunction, Extrinsics } from '@polkadot/extrinsics/types';
import { AnyU8a, Codec, Constructor } from './types';
import { assert, isHex, isObject, isU8a } from '@polkadot/util';
import { AnyU8a, Codec, Constructor } from './types';
import { FunctionMetadata, FunctionArgumentMetadata } from './Metadata';
import { getTypeDef, getTypeClass } from './codec/createType';
import Struct from './codec/Struct';
import U8aFixed from './codec/U8aFixed';
import Extrinsic from './Extrinsic';
import { FunctionMetadata, FunctionArgumentMetadata } from './Metadata';
const FN_UNKNOWN = {
method: 'unknown',
@@ -30,6 +31,23 @@ interface DecodedMethod extends DecodeMethodInput {
meta: FunctionMetadata;
}
export interface ExtrinsicFunction {
(...args: any[]): Extrinsic;
callIndex: Uint8Array;
meta: FunctionMetadata;
method: string;
section: string;
toJSON: () => any;
}
export interface ModuleExtrinsics {
[key: string]: ExtrinsicFunction;
}
export interface Extrinsics {
[key: string]: ModuleExtrinsics; // Will hold modules returned by state_getMetadata
}
const extrinsicFns: { [index: string]: ExtrinsicFunction } = {};
class MethodIndex extends U8aFixed {
+5 -8
View File
@@ -2,10 +2,10 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { isFunction, isString, stringToU8a, u8aToString, u8aConcat, u8aToHex } from '@polkadot/util';
import { isFunction, isString, stringToU8a, u8aToString, u8aToHex } from '@polkadot/util';
import { AnyU8a, Codec } from './types';
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
import Compact from './codec/Compact';
// This is a string wrapper, along with the length. It is used both for strings as well
// as stuff like documentation.
@@ -26,7 +26,7 @@ export default class Text extends String implements Codec {
if (isString(value)) {
return value.toString();
} else if (value instanceof Uint8Array) {
const [offset, length] = Compact.decodeU8a(value, DEFAULT_LENGTH_BITS);
const [offset, length] = Compact.decodeU8a(value);
return u8aToString(value.subarray(offset, offset + length.toNumber()));
} else if (isFunction(value.toString)) {
@@ -37,7 +37,7 @@ export default class Text extends String implements Codec {
}
get encodedLength (): number {
return this.length + Compact.encodeU8a(this.length, DEFAULT_LENGTH_BITS).length;
return this.length + Compact.encodeU8a(this.length).length;
}
toHex (): string {
@@ -53,9 +53,6 @@ export default class Text extends String implements Codec {
return isBare
? encoded
: u8aConcat(
Compact.encodeU8a(this.length, DEFAULT_LENGTH_BITS),
encoded
);
: Compact.addLengthPrefix(encoded);
}
}
+2 -2
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
import Compact from './codec/Compact';
import U8a from './codec/U8a';
import Text from './Text';
@@ -62,7 +62,7 @@ export default class Type extends Text {
// length of the data. Since toU8a is disabled, this does not affect encoding, but rather
// only the decoding leg, allowing the decoders to work with original pointers
get encodedLength (): number {
return this._originalLength + Compact.encodeU8a(this._originalLength, DEFAULT_LENGTH_BITS).length;
return this._originalLength + Compact.encodeU8a(this._originalLength).length;
}
// Note Since we are mangling what we get in beyond recognition, we really should
+8 -54
View File
@@ -3,19 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { bnToBn, bnToU8a, hexToBn, isBn, isHex, isNumber, isString, isU8a, u8aToBn, u8aConcat, u8aToU8a } from '@polkadot/util';
import { bnToBn, compactAddLength, compactFromU8a, compactStripLength, compactToU8a, hexToBn, isBn, isHex, isNumber, isString, isU8a } from '@polkadot/util';
import { DEFAULT_BITLENGTH } from '@polkadot/util/compact/defaults';
import { AnyNumber, Codec, Constructor } from '../types';
import Base from './Base';
import UInt, { UIntBitLength } from './UInt';
import Moment from '../Moment';
export const DEFAULT_LENGTH_BITS = 32;
const MAX_U8 = new BN(2).pow(new BN(8 - 2)).subn(1);
const MAX_U16 = new BN(2).pow(new BN(16 - 2)).subn(1);
const MAX_U32 = new BN(2).pow(new BN(32 - 2)).subn(1);
// A new compact length-encoding algorithm. It performs the same function as Length, however
// differs in that it uses a variable number of bytes to do the actual encoding. From the Rust
// implementation for compact encoding
@@ -49,17 +44,14 @@ export default class Compact extends Base<UInt | Moment> implements Codec {
*
* @param u8a - The Uint8Array to be prefixed
*/
static addLengthPrefix (u8a: Uint8Array, bitLength: UIntBitLength = DEFAULT_LENGTH_BITS): Uint8Array {
return u8aConcat(
Compact.encodeU8a(u8a.length, bitLength),
u8a
);
}
static addLengthPrefix = compactAddLength;
static decodeU8a = compactFromU8a;
static encodeU8a = compactToU8a;
static stripLengthPrefix (u8a: Uint8Array, bitLength: UIntBitLength = DEFAULT_LENGTH_BITS): Uint8Array {
const [offset] = Compact.decodeU8a(u8a, bitLength);
static stripLengthPrefix (u8a: Uint8Array, bitLength: UIntBitLength = DEFAULT_BITLENGTH): Uint8Array {
const [_, value] = compactStripLength(u8a, bitLength);
return u8a.subarray(offset);
return value;
}
static decodeCompact (Type: Constructor<UInt | Moment>, value: AnyNumber): Moment | UInt {
@@ -80,44 +72,6 @@ export default class Compact extends Base<UInt | Moment> implements Codec {
return new Type(value.toBn());
}
static decodeU8a (_input: Uint8Array | string, bitLength: UIntBitLength): [number, BN] {
const input = u8aToU8a(_input);
const flag = input[0] & 0b11;
if (flag === 0b00) {
return [1, new BN(input[0]).shrn(2)];
} else if (flag === 0b01) {
return [2, u8aToBn(input.slice(0, 2), true).shrn(2)];
} else if (flag === 0b10) {
return [4, u8aToBn(input.slice(0, 4), true).shrn(2)];
}
const byteLength = bitLength / 8;
return [byteLength + 1, u8aToBn(input.subarray(1, 1 + byteLength), true)];
}
static encodeU8a (_value: UInt | BN | number, bitLength: UIntBitLength): Uint8Array {
const value = _value instanceof UInt
? _value.toBn()
: bnToBn(_value);
if (value.lte(MAX_U8)) {
return new Uint8Array([value.toNumber() << 2]);
} else if (value.lte(MAX_U16)) {
return bnToU8a(value.shln(2).addn(0b01), 16, true);
} else if (value.lte(MAX_U32)) {
return bnToU8a(value.shln(2).addn(0b10), 32, true);
}
return u8aConcat(
new Uint8Array([
0b11
]),
bnToU8a(value, bitLength, true)
);
}
bitLength (): UIntBitLength {
return this.raw.bitLength();
}
@@ -13,15 +13,16 @@ import Proposal from '../Proposal';
import VoteThreshold from '../VoteThreshold';
describe('Tuple', () => {
let tuple;
let tuple: Tuple;
beforeEach(() => {
Method.injectExtrinsics(extrinsics);
// FIXME something weird here, injecting any :(
tuple = new Tuple({
foo: Text,
bar: U32
}, { foo: 'foo', bar: 69 });
} as any, { foo: 'foo', bar: 69 });
});
it('returns array with toJSON', () => {
@@ -58,8 +59,8 @@ describe('Tuple', () => {
threshold: VoteThreshold
}))('0x62190000000000000003507b0a092230783432223a202230783433220a7d0a01');
expect(test.getAtIndex(0).toNumber()).toEqual(6498);
expect(test.getAtIndex(1).callIndex).toEqual(new Uint8Array([0, 3]));
expect(test.getAtIndex(2).toNumber()).toEqual(1);
expect((test.getAtIndex(0) as BlockNumber).toNumber()).toEqual(6498);
expect((test.getAtIndex(1) as Method).callIndex).toEqual(new Uint8Array([0, 3]));
expect((test.getAtIndex(2) as VoteThreshold).toNumber()).toEqual(1);
});
});
+4 -4
View File
@@ -4,7 +4,7 @@
import { u8aConcat, u8aToU8a, u8aToHex } from '@polkadot/util';
import Compact, { DEFAULT_LENGTH_BITS } from './Compact';
import Compact from './Compact';
import { Codec, Constructor } from '../types';
// This manages codec arrays. Intrernally it keeps track of the length (as decoded) and allows
@@ -36,7 +36,7 @@ export default class Vector<
const u8a = u8aToU8a(value);
let [offset, _length] = Compact.decodeU8a(u8a, DEFAULT_LENGTH_BITS);
let [offset, _length] = Compact.decodeU8a(u8a);
const length = _length.toNumber();
const result = [];
@@ -66,7 +66,7 @@ export default class Vector<
get encodedLength (): number {
return this.reduce((total, raw) => {
return total + raw.encodedLength;
}, Compact.encodeU8a(this.length, DEFAULT_LENGTH_BITS).length);
}, Compact.encodeU8a(this.length).length);
}
toArray (): Array<T> {
@@ -100,7 +100,7 @@ export default class Vector<
return isBare
? u8aConcat(...encoded)
: u8aConcat(
Compact.encodeU8a(this.length, DEFAULT_LENGTH_BITS),
Compact.encodeU8a(this.length),
...encoded
);
}