diff --git a/packages/api-codec/package.json b/packages/api-codec/package.json index 4c1bfa61ca..d64c51adf0 100644 --- a/packages/api-codec/package.json +++ b/packages/api-codec/package.json @@ -30,6 +30,7 @@ "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-codec#readme", "dependencies": { "@babel/runtime": "^7.0.0", - "@polkadot/util": "^0.30.4" + "@polkadot/util": "^0.30.4", + "@polkadot/util-keyring": "^0.30.4" } } diff --git a/packages/api-codec/src/AccountId.spec.js b/packages/api-codec/src/AccountId.spec.js new file mode 100644 index 0000000000..a8cd3384d5 --- /dev/null +++ b/packages/api-codec/src/AccountId.spec.js @@ -0,0 +1,54 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import AccountId from './AccountId'; + +describe('AccountId', () => { + it('decodes from u8a', () => { + expect( + new AccountId() + .fromU8a( + new Uint8Array([ + 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, + 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 + ]) + ) + .toString() + ).toEqual( + '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s' + ); + }); + + it('decodes from address', () => { + expect( + new AccountId() + .fromJSON('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s') + .toHex() + ).toEqual( + '0x0102030405060708010203040506070801020304050607080102030405060708' + ); + }); + + it('decodes from hex', () => { + expect( + new AccountId() + .fromJSON('0x0102030405060708010203040506070801020304050607080102030405060708') + .toJSON() + ).toEqual( + '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s' + ); + }); + + it('allows creation from another', () => { + expect( + new AccountId( + new AccountId( + '0x0102030405060708010203040506070801020304050607080102030405060708' + ) + ).toString() + ).toEqual( + '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s' + ); + }); +}); diff --git a/packages/api-codec/src/AccountId.ts b/packages/api-codec/src/AccountId.ts new file mode 100644 index 0000000000..06f8113913 --- /dev/null +++ b/packages/api-codec/src/AccountId.ts @@ -0,0 +1,61 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import encodeAddress from '@polkadot/util-keyring/address/encode'; +import decodeAddress from '@polkadot/util-keyring/address/decode'; +import hexToU8a from '@polkadot/util/hex/toU8a'; +import isHex from '@polkadot/util/is/hex'; +import isU8a from '@polkadot/util/is/u8a'; +import u8aToU8a from '@polkadot/util/u8a/toU8a'; + +import CodecU8a from './codec/U8a'; +import CodecU8aFixed from './codec/U8aFixed'; + +// A wrapper around an AccountId/PublicKey representation. Since we are dealing with +// underlying PublicKeys (32 bytes in length), we extend from CodecU8aFixed which is +// basically just a Uint8Array wrapper with a fixed length. +export default class AccountId extends CodecU8aFixed { + constructor (value: CodecU8a | string | Uint8Array = new Uint8Array()) { + super( + value instanceof CodecU8a + ? value.raw + : AccountId.decode(value), + 256 + ); + } + + static encode (value: Uint8Array): string { + return encodeAddress(value); + } + + static decode (value: string | Uint8Array | Array): Uint8Array { + if (isU8a(value) || Array.isArray(value)) { + return u8aToU8a(value); + } else if (isHex(value)) { + return hexToU8a(value); + } + + return decodeAddress(value); + } + + fromJSON (input: any): AccountId { + super.fromJSON(AccountId.decode(input)); + + return this; + } + + fromU8a (input: Uint8Array): AccountId { + super.fromU8a(input); + + return this; + } + + toJSON (): any { + return this.toString(); + } + + toString (): string { + return AccountId.encode(this.raw); + } +} diff --git a/packages/api-codec/src/AccountIndex.ts b/packages/api-codec/src/AccountIndex.ts new file mode 100644 index 0000000000..6a08d36c49 --- /dev/null +++ b/packages/api-codec/src/AccountIndex.ts @@ -0,0 +1,63 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import hexToU8a from '@polkadot/util/hex/toU8a'; +import isHex from '@polkadot/util/is/hex'; +import isU8a from '@polkadot/util/is/u8a'; +import u8aToHex from '@polkadot/util/u8a/toHex'; +import u8aToU8a from '@polkadot/util/u8a/toU8a'; + +import CodecU8a from './codec/U8a'; + +// A wrapper around an AccountIndex, which is a shortened, variable-length encoding +// for an Account. We extends from CodecU8a which is basically +// just a Uint8Array wrapper. +export default class AccountIndex extends CodecU8a { + constructor (value: CodecU8a | string | Uint8Array = new Uint8Array()) { + super( + value instanceof CodecU8a + ? value.raw + : AccountIndex.decode(value) + ); + } + + // FIXME Not 100% sure how to handle the encoding of short addresses. It is (mostly) + // unused atm, options are to go to hex or to utf8. Here we go the hex route. + static encode (value: Uint8Array): string { + return u8aToHex(value); + } + + static decode (value: string | Uint8Array | Array): Uint8Array { + if (isU8a(value) || Array.isArray(value)) { + return u8aToU8a(value); + } else if (isHex(value)) { + return hexToU8a(value); + } + + throw new Error(`Unable to decode AccountIndex for [${value.toString()}]`); + } + + fromJSON (input: any): AccountIndex { + super.fromJSON(AccountIndex.decode(input)); + + return this; + } + + // TODO Without specific data and actual real-world tests, unsure about how the + // actual encoding here fits together. It is quite possibly prefix-encoded, so + // prefixes may have to be stripped. + fromU8a (input: Uint8Array): AccountIndex { + super.fromU8a(input); + + return this; + } + + toJSON (): any { + return this.toString(); + } + + toString (): string { + return AccountIndex.encode(this.raw); + } +} diff --git a/packages/api-codec/src/Address.spec.js b/packages/api-codec/src/Address.spec.js new file mode 100644 index 0000000000..112f386e9b --- /dev/null +++ b/packages/api-codec/src/Address.spec.js @@ -0,0 +1,89 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import Address from './Address'; + +describe('Address', () => { + it('decodes with a prefix (255)', () => { + expect( + new Address() + .fromU8a( + new Uint8Array([ + 255, + 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, + 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 + ]) + ) + .toString() + ).toEqual('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s'); + }); + + it('encodes with a prefix', () => { + expect( + new Address() + .fromJSON('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCt72s') + .toU8a() + ).toEqual( + new Uint8Array([ + 255, + 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, + 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 + ]) + ); + }); + + it('decodes with a prefix (1-byte)', () => { + expect( + new Address() + .fromU8a( + new Uint8Array([ + 1, 17 + ]) + ) + .toString() + ).toEqual('0x11'); + }); + + it('decodes with a prefix (2-bytes)', () => { + expect( + new Address() + .fromU8a( + new Uint8Array([ + 0xfc, 17, 18 + ]) + ) + .toString() + ).toEqual('0x1112'); + }); + + it('decodes with a prefix (4-bytes)', () => { + expect( + new Address() + .fromU8a( + new Uint8Array([ + 0xfd, 17, 18, 19, 20 + ]) + ) + .toString() + ).toEqual('0x11121314'); + }); + + it('decodes with a prefix (8-bytes)', () => { + expect( + new Address() + .fromU8a( + new Uint8Array([ + 0xfe, 17, 18, 19, 20, 21, 22, 23, 24 + ]) + ) + .toString() + ).toEqual('0x1112131415161718'); + }); + + it('fails to code invalid lengths', () => { + expect( + () => Address.writeLength(34) + ).toThrow(/Invalid bitLength/); + }); +}); diff --git a/packages/api-codec/src/Address.ts b/packages/api-codec/src/Address.ts new file mode 100644 index 0000000000..cd7abd9c9a --- /dev/null +++ b/packages/api-codec/src/Address.ts @@ -0,0 +1,118 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import isHex from '@polkadot/util/is/hex'; +import isU8a from '@polkadot/util/is/u8a'; +import u8aConcat from '@polkadot/util/u8a/concat'; +import u8aToU8a from '@polkadot/util/u8a/toU8a'; + +import CodecBase from './codec/Base'; +import AccountId from './AccountId'; +import AccountIndex from './AccountIndex'; + +// A wrapper around an AccountId and/or AccountIndex that is encoded with a prefix. +// Since we are dealing with underlying publicKeys (or shorter encoded addresses), +// we extend from Base with an AccountId/AccountIndex wrapper. Basically the Address +// is encoded as +// [ , ...publicKey/...bytes ] +export default class Address extends CodecBase { + constructor (value: Address | AccountId | AccountIndex | string | Uint8Array = new Uint8Array()) { + super( + value instanceof Address + ? value.raw + : Address.decode(value) + ); + } + + static decode (value: AccountId | AccountIndex | string | Uint8Array | Array): AccountId | AccountIndex { + if (value instanceof AccountId || value instanceof AccountIndex) { + return value; + } else if (isU8a(value) || Array.isArray(value)) { + return value.length === 32 + ? new AccountId(u8aToU8a(value)) + : new AccountIndex(u8aToU8a(value)); + } else if (isHex(value)) { + return value.length === 66 + ? new AccountId(value) + : new AccountIndex(value); + } + + // FIXME This _may_ be an issue. Depending on how the actual AccountIndex is + // actually encoded as a string. Here we just assume that it is an ss-58 value + // and use the stock-stand AccountId as PublicKey + return new AccountId(value); + } + + // TODO + // - Double-check this logic again - if really <= 0xef, the throw + // is unneeded since all cases are catered for here + // - We probably want to clean the read/write up with enums if it + // is an exact check and not a <= check (first item) + static readLength (input: Uint8Array): number { + const first = input[0]; + + if (first <= 0xef) { + return 1; + } else if (first === 0xfc) { + return 2; + } else if (first === 0xfd) { + return 4; + } else if (first === 0xfe) { + return 8; + } else if (first === 0xff) { + return 32; + } + + throw new Error(`Invalid account index byte, 0x${first.toString(16)}`); + } + + static writeLength (length: number): Uint8Array { + if (length === 1) { + return new Uint8Array([0xef]); + } else if (length === 2) { + return new Uint8Array([0xfc]); + } else if (length === 4) { + return new Uint8Array([0xfd]); + } else if (length === 8) { + return new Uint8Array([0xfe]); + } else if (length === 32) { + return new Uint8Array([0xff]); + } + + throw new Error(`Invalid bitLength, ${length * 8}`); + } + + byteLength (): number { + return 1 + super.byteLength(); + } + + fromJSON (input: any): Address { + this.raw = Address.decode(input); + + return this; + } + + fromU8a (input: Uint8Array): Address { + this.raw = Address.readLength(input) === 32 + ? new AccountId().fromU8a(input.subarray(1)) + : new AccountIndex().fromU8a(input.subarray(1)); + + return this; + } + + toJSON (): any { + return this.raw.toJSON(); + } + + toString (): string { + return this.raw.toString(); + } + + toU8a (): Uint8Array { + return u8aConcat( + Address.writeLength(this.raw.byteLength()), + this.raw.toU8a() + ); + } +} diff --git a/packages/api-codec/src/Balance.ts b/packages/api-codec/src/Balance.ts new file mode 100644 index 0000000000..626026c299 --- /dev/null +++ b/packages/api-codec/src/Balance.ts @@ -0,0 +1,9 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import U128 from './U128'; + +// The Substrate Balance representation. +export default class Balance extends U128 { +} diff --git a/packages/api-codec/src/BlockNumber.ts b/packages/api-codec/src/BlockNumber.ts new file mode 100644 index 0000000000..eac1c1218a --- /dev/null +++ b/packages/api-codec/src/BlockNumber.ts @@ -0,0 +1,8 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import U64 from './U64'; + +export default class BlockNumber extends U64 { +} diff --git a/packages/api-codec/src/Bool.ts b/packages/api-codec/src/Bool.ts new file mode 100644 index 0000000000..bbb05d8951 --- /dev/null +++ b/packages/api-codec/src/Bool.ts @@ -0,0 +1,43 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import CodecBase from './codec/Base'; + +export default class Bool extends CodecBase { + constructor (value: Bool | boolean = false) { + super( + value instanceof Bool + ? value.raw + : value + ); + } + + byteLength (): number { + return 1; + } + + fromJSON (input: any): Bool { + this.raw = input === true; + + return this; + } + + fromU8a (input: Uint8Array): Bool { + this.raw = input[0] === 1; + + return this; + } + + toJSON (): any { + return this.raw; + } + + toU8a (): Uint8Array { + return new Uint8Array([this.raw ? 1 : 0]); + } + + toString (): string { + return `${this.raw}`; + } +} diff --git a/packages/api-codec/src/H256.ts b/packages/api-codec/src/H256.ts new file mode 100644 index 0000000000..8c3fafe90e --- /dev/null +++ b/packages/api-codec/src/H256.ts @@ -0,0 +1,14 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import CodecU8a from './codec/U8a'; +import CodecU8aFixed from './codec/U8aFixed'; + +// Hash containing 256 bits (32 bytes), typically used in blocks, extrinsics and +// as a sane default for fixed-length hash representations. +export default class H256 extends CodecU8aFixed { + constructor (value?: CodecU8a | Uint8Array) { + super(value, 256); + } +} diff --git a/packages/api-codec/src/H512.ts b/packages/api-codec/src/H512.ts new file mode 100644 index 0000000000..2c713a3ac7 --- /dev/null +++ b/packages/api-codec/src/H512.ts @@ -0,0 +1,13 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import CodecU8a from './codec/U8a'; +import CodecU8aFixed from './codec/U8aFixed'; + +// Hash containing 512 bits (64 bytes), typically used for signatures +export default class H512 extends CodecU8aFixed { + constructor (value?: CodecU8a | Uint8Array) { + super(value, 512); + } +} diff --git a/packages/api-codec/src/Hash.ts b/packages/api-codec/src/Hash.ts new file mode 100644 index 0000000000..757f71fc3a --- /dev/null +++ b/packages/api-codec/src/Hash.ts @@ -0,0 +1,10 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import H256 from './H256'; + +// The default hash that is used accross the system. It is basically just a thin +// wrapper around H256, representing a 32-byte blake2b (Substrate) value +export default class Hash extends H256 { +} diff --git a/packages/api-codec/src/Header.only.json b/packages/api-codec/src/Header.only.json new file mode 100644 index 0000000000..7a3909f0b5 --- /dev/null +++ b/packages/api-codec/src/Header.only.json @@ -0,0 +1 @@ +{"digest":{"logs":[]},"extrinsicsRoot":"0x45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0","number":0,"parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","stateRoot":"0x294c3470ae3be7555240b9d034ec19c3715ba2c3f20b92441f8cea0cab66ab56"} diff --git a/packages/api-codec/src/Header.spec.js b/packages/api-codec/src/Header.spec.js new file mode 100644 index 0000000000..4384c3eebd --- /dev/null +++ b/packages/api-codec/src/Header.spec.js @@ -0,0 +1,30 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import Header from './Header'; +import json from './Header.only.json'; + +describe('Header', () => { + it('decodes an actual JSON response', () => { + const header = new Header(); + + header.fromJSON(json); + + expect( + header.blockNumber.toNumber() + ).toEqual(0); + expect( + header.extrinsicsRoot.toString() + ).toEqual('0x45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0'); + expect( + header.parentHash.toString() + ).toEqual('0x0000000000000000000000000000000000000000000000000000000000000000'); + expect( + header.stateRoot.toString() + ).toEqual('0x294c3470ae3be7555240b9d034ec19c3715ba2c3f20b92441f8cea0cab66ab56'); + expect( + header.digest.logs.toString() + ).toEqual('[]'); + }); +}); diff --git a/packages/api-codec/src/Header.ts b/packages/api-codec/src/Header.ts new file mode 100644 index 0000000000..3272e523d0 --- /dev/null +++ b/packages/api-codec/src/Header.ts @@ -0,0 +1,56 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import CodecArray from './codec/Array'; +import CodecBytes from './codec/Bytes'; +import CodecStruct from './codec/Struct'; + +import BlockNumber from './BlockNumber'; +import Hash from './Hash'; + +// A block header digest. +export class Digest extends CodecStruct { + constructor (value?: any) { + super({ + logs: CodecArray.with(CodecBytes) + }, value); + } + + get logs (): CodecArray { + return this.raw.logs as CodecArray; + } +} + +// A block header. +export default class Header extends CodecStruct { + constructor (value?: any) { + super({ + parentHash: Hash, + number: BlockNumber, + stateRoot: Hash, + extrinsicsRoot: Hash, + digest: Digest + }, value); + } + + get blockNumber (): BlockNumber { + return this.raw.number as BlockNumber; + } + + get digest (): Digest { + return this.raw.digest as Digest; + } + + get extrinsicsRoot (): Hash { + return this.raw.extrinsicsRoot as Hash; + } + + get parentHash (): Hash { + return this.raw.parentHash as Hash; + } + + get stateRoot (): Hash { + return this.raw.stateRoot as Hash; + } +} diff --git a/packages/api-codec/src/Index.ts b/packages/api-codec/src/Index.ts new file mode 100644 index 0000000000..f53f965789 --- /dev/null +++ b/packages/api-codec/src/Index.ts @@ -0,0 +1,10 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import U32 from './U32'; + +// The Nonce or number of transactiosn sent by a specific account. Generally used +// with extrinsics to determine the order of execution. +export default class Index extends U32 { +} diff --git a/packages/api-codec/src/KeyValue.spec.js b/packages/api-codec/src/KeyValue.spec.js new file mode 100644 index 0000000000..d9772cee28 --- /dev/null +++ b/packages/api-codec/src/KeyValue.spec.js @@ -0,0 +1,49 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import KeyValue from './KeyValue'; + +describe('KeyValue', () => { + it('decodes KeyValue from u8a', () => { + expect( + new KeyValue().fromU8a( + new Uint8Array([ + 4 << 2, + 0x11, 0x22, 0x33, 0x44, + 9 << 2, + 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 + ]) + ).toJSON() + ).toEqual({ + key: '0x11223344', + value: '0x998877665544332211' + }); + }); + + it('encodes KeyValue from JSON', () => { + expect( + new KeyValue().fromJSON({ + key: '0x11223344', + value: '0x998877665544332211' + }).toU8a() + ).toEqual( + new Uint8Array([ + 4 << 2, + 0x11, 0x22, 0x33, 0x44, + 9 << 2, + 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 + ]) + ); + }); + + it('exposes the properties for key/value', () => { + const kv = new KeyValue({ + key: '0x11223344', + value: '0x998877665544332211' + }); + + expect(kv.key.toHex()).toEqual('0x11223344'); + expect(kv.value.toHex()).toEqual('0x998877665544332211'); + }); +}); diff --git a/packages/api-codec/src/KeyValue.ts b/packages/api-codec/src/KeyValue.ts new file mode 100644 index 0000000000..088e9efd08 --- /dev/null +++ b/packages/api-codec/src/KeyValue.ts @@ -0,0 +1,32 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import CodecBytes from './codec/Bytes'; +import CodecStruct from './codec/Struct'; + +type KeyValueStruct = { + key: Uint8Array, + value: Uint8Array +}; + +// KeyValue structure. Since most of the keys and resultant values in Subtrate is +// hashed and/or encoded, this does not wrap a CodecString, but rather a CodecBytes +// for the keys and values. (Not to be confused with the KeyValue in Metadata, that +// is actually for Maps, whereas this is a representation of actaul storage values) +export default class KeyValue extends CodecStruct { + constructor (value: KeyValueStruct = {} as KeyValueStruct) { + super({ + key: CodecBytes, + value: CodecBytes + }, value); + } + + get key (): CodecBytes { + return this.raw.key as CodecBytes; + } + + get value (): CodecBytes { + return this.raw.value as CodecBytes; + } +} diff --git a/packages/api-codec/src/Metadata.decoded.json b/packages/api-codec/src/Metadata.decoded.json index 01f758d840..894a501dd3 100644 --- a/packages/api-codec/src/Metadata.decoded.json +++ b/packages/api-codec/src/Metadata.decoded.json @@ -676,7 +676,7 @@ ] }, { - "name": "TransactionCodecBaseFee", + "name": "TransactionBaseFee", "modifier": 2, "type": "T::Balance", "documentation": [ diff --git a/packages/api-codec/src/Metadata.spec.js b/packages/api-codec/src/Metadata.spec.js index 1277e08863..5d505c67af 100644 --- a/packages/api-codec/src/Metadata.spec.js +++ b/packages/api-codec/src/Metadata.spec.js @@ -7,8 +7,8 @@ import rpcdata from './Metadata.rpc.json'; describe('Metadata', () => { it('decodes properly', () => { - const decoded = new Metadata().fromU8a( - Uint8Array.from(rpcdata.result) + const decoded = new Metadata().fromJSON( + rpcdata.result ); const str = JSON.stringify(decoded.toJSON()); diff --git a/packages/api-codec/src/Metadata.ts b/packages/api-codec/src/Metadata.ts index 2df16d46ad..f8218f81c8 100644 --- a/packages/api-codec/src/Metadata.ts +++ b/packages/api-codec/src/Metadata.ts @@ -2,12 +2,12 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. -import CodecArray from './base/Array'; -import CodecBase from './base/Base'; -import CodecEnum from './base/Enum'; -import CodecEnumType from './base/EnumType'; -import CodecOption from './base/Option'; -import CodecStruct from './base/Struct'; +import CodecArray from './codec/Array'; +import CodecBase from './codec/Base'; +import CodecEnum from './codec/Enum'; +import CodecEnumType from './codec/EnumType'; +import CodecOption from './codec/Option'; +import CodecStruct from './codec/Struct'; import String from './String'; import Type from './Type'; import U16 from './U16'; @@ -268,6 +268,18 @@ export default class RuntimeMetadata extends CodecStruct { }, value); } + // We receive this a an Array in the JSON output from the Node. Convert + // to u8a and use the fromU8a to do the actual parsing + // + // FIXME Currently toJSON creates a struct, so it is not a one-to-one mapping + // with what is actually found on the RPC layer. This needs to be adjusted to + // match. (However for now, it is useful in debugging) + fromJSON (input: Array): RuntimeMetadata { + return this.fromU8a( + Uint8Array.from(input) + ) as RuntimeMetadata; + } + // FIXME Really not crazy about having to manually add all the getters. Preferably it should // be done automagically in the actual CodecStruct - however what is really important here // here is that we should nbot lose the autocompletion and checking that TS gives us. So if @@ -292,15 +304,6 @@ export default class RuntimeMetadata extends CodecStruct { : entry ); }, []); - // Quick and dirty uniq - const uniq = (list: Array): Array => - list.reduce((result, entry) => { - if (!result.includes(entry)) { - result.push(entry); - } - - return result; - }, [] as Array); const events = this.events.map((module) => module.events.map((event) => @@ -326,8 +329,8 @@ export default class RuntimeMetadata extends CodecStruct { ) ); - return uniq( + return [...new Set( flatten([events, storages, args]).filter((value) => value) - ).sort(); + )].sort(); } } diff --git a/packages/api-codec/src/ProposalIndex.ts b/packages/api-codec/src/ProposalIndex.ts new file mode 100644 index 0000000000..d2d73ce3f5 --- /dev/null +++ b/packages/api-codec/src/ProposalIndex.ts @@ -0,0 +1,9 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import U32 from './U32'; + +// An increasing number that represents a specific proposal in the system +export default class ProposalIndex extends U32 { +} diff --git a/packages/api-codec/src/ReferendumIndex.ts b/packages/api-codec/src/ReferendumIndex.ts new file mode 100644 index 0000000000..f28691c5b2 --- /dev/null +++ b/packages/api-codec/src/ReferendumIndex.ts @@ -0,0 +1,10 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import U32 from './U32'; + +// An increasing number that represents a specific referendum in the system. It +// is unique per chain. +export default class ReferendumIndex extends U32 { +} diff --git a/packages/api-codec/src/Signature.ts b/packages/api-codec/src/Signature.ts new file mode 100644 index 0000000000..9bb2ea27f4 --- /dev/null +++ b/packages/api-codec/src/Signature.ts @@ -0,0 +1,10 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import H512 from './H512'; + +// The default signature that is used accross the system. It is currectly defined +// as a 512-bit value, represented by a hash. +export default class Signature extends H512 { +} diff --git a/packages/api-codec/src/String.ts b/packages/api-codec/src/String.ts index b9df6c6441..3bae4651d1 100644 --- a/packages/api-codec/src/String.ts +++ b/packages/api-codec/src/String.ts @@ -6,8 +6,8 @@ import u8aFromUtf8 from '@polkadot/util/u8a/fromUtf8'; import u8aToUtf8 from '@polkadot/util/u8a/toUtf8'; import u8aConcat from '@polkadot/util/u8a/concat'; -import CodecBase from './base/Base'; -import Length from './base/LengthCompact'; +import CodecBase from './codec/Base'; +import Length from './codec/Length'; // This is a string wrapper, along with the length. It is used both for strings as well // as stuff like documentation. @@ -20,8 +20,12 @@ import Length from './base/LengthCompact'; export default class String extends CodecBase { protected _length: Length; - constructor (value: string = '') { - super(value); + constructor (value: String | string = '') { + super( + value instanceof String + ? value.raw + : value + ); this._length = new Length(value.length); } @@ -38,7 +42,9 @@ export default class String extends CodecBase { } fromJSON (input: any): String { - throw new Error('String::fromJSON: unimplemented'); + this.raw = `${input}`; + + return this; } fromU8a (input: Uint8Array): String { diff --git a/packages/api-codec/src/Type.spec.js b/packages/api-codec/src/Type.spec.js new file mode 100644 index 0000000000..f3bf369303 --- /dev/null +++ b/packages/api-codec/src/Type.spec.js @@ -0,0 +1,31 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import Type from './Type'; + +describe('Type', () => { + it('fails to cleanup invalid boxes', () => { + expect( + () => new Type().fromJSON('Box { + expect( + new Type().fromJSON('Box>').toString() + ).toEqual('Vec'); + }); + + it('handles aliasses, multiples per line', () => { + expect( + new Type().fromJSON('(PropIndex, AccountId, PropIndex)').toString() + ).toEqual('(ProposalIndex, AccountId, ProposalIndex)'); + }); + + it('does not allow toU8a', () => { + expect( + () => new Type().toU8a() + ).toThrow(/unimplemented/); + }); +}); diff --git a/packages/api-codec/src/Type.ts b/packages/api-codec/src/Type.ts index 3883241d23..446743950c 100644 --- a/packages/api-codec/src/Type.ts +++ b/packages/api-codec/src/Type.ts @@ -4,93 +4,129 @@ import String from './String'; -// given a starting index, find the closing > -function findClosing (value: string, start: number): number { - let depth = 0; - - for (let index = start; index < value.length; index++) { - if (value[index] === '>') { - if (!depth) { - return index; - } else { - depth--; - } - } else if (value[index] === '<') { - depth++; - } - } - - throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`); -} - -function ungeneric (value: string): string { - for (let index = 0; index < value.length; index++) { - if (value[index] === '<') { - if (value.substr(index - 3, 3) !== 'Vec') { - const start = index + 1; - const end = findClosing(value, start); - - value = `${value.substr(0, index)}${value.substr(end + 1)}`; - } - } - } - - return value; -} - -// remove the type traits -function untrait (value: string): string { - return value - // anything `T::` to end up as `` - .replace(/T::/g, '') - // `system::` with `` - basically we find `` - .replace(/system::/g, '') - // replace `::` (possibly sanitiused just above) - .replace(/::/g, ''); -} - -// remove wrapping values, i.e. Box -> Proposal -function unwrap (check: string, value: string): string { - let index = 0; - - while (index !== -1) { - index = value.indexOf(check); - - if (index !== -1) { - const start = index + check.length; - const end = findClosing(value, start); - - value = `${value.substr(start, end - start)}`; - } - } - - return value; -} +type Mapper = (value: string) => string; // This is a extended version of String, specifically to handle types. Here we rely full on // what string provides us, however we also "tweak" the types received from the runtime, i.e. // we remove the `T::` prefixes found in some types for consistency accross implementation. export default class Type extends String { - fromU8a (input: Uint8Array): String { + fromJSON (input: any): Type { + super.fromJSON(input); + + return this._cleanupTypes(); + } + + fromU8a (input: Uint8Array): Type { super.fromU8a(input); - // Hack around the Rust types to make them consistent for actual use - let result = untrait(this.raw); + return this._cleanupTypes(); + } - // `Box` -> `Proposal` - result = unwrap('Box<', result); - // `MisbehaviorReport` -> `MisbehaviorReport` - result = ungeneric(result); + // Note Since we are mangling what we get in beyond recognition, we really should + // not allow the re-encoding. Additionally, this is probably more of a decoder-only + // helper, so treat it as such. + toU8a (): Uint8Array { + throw new Error('Type::toU8a: unimplemented'); + } - this.raw = result; + // HACK(ery) Take the types and tweak them (slightly?) for consistency + private _cleanupTypes (): Type { + const mappings: Array = [ + // Remove all the trait prefixes + this._untrait(), + // remove boxing, `Box` -> `Proposal` + this._unwrap('Box<'), + // remove generics, `MisbehaviorReport` -> `MisbehaviorReport` + this._ungeneric(), + // convert `RawAddress` -> `Address` + this._unalias('RawAddress', 'Address'), + // convert `PropIndex` -> `ProposalIndex` + this._unalias('PropIndex', 'ProposalIndex') + ]; + + this.raw = mappings.reduce((result, fn) => { + return fn(result); + }, this.raw); return this; } - toU8a (): Uint8Array { - // Note Since we are mangling what we get in beyond recognition, we really should - // not allow the re-encoding. Additionally, this is probably more of a decoder-only - // helper, so treat it as such. - throw new Error('Type::toU8a: unimplemented'); + // given a starting index, find the closing > + private _findClosing (value: string, start: number): number { + let depth = 0; + + for (let index = start; index < value.length; index++) { + if (value[index] === '>') { + if (!depth) { + return index; + } else { + depth--; + } + } else if (value[index] === '<') { + depth++; + } + } + + throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`); + } + + private _unalias (src: string, dest: string): Mapper { + return (value: string): string => { + while (value.indexOf(src) !== -1) { + value = value.replace(src, dest); + } + + return value; + }; + } + + private _ungeneric (): Mapper { + return (value: string): string => { + for (let index = 0; index < value.length; index++) { + if (value[index] === '<') { + if (value.substr(index - 3, 3) !== 'Vec') { + const start = index + 1; + const end = this._findClosing(value, start); + + value = `${value.substr(0, index)}${value.substr(end + 1)}`; + } + } + } + + return value; + }; + } + + // remove the type traits + private _untrait (): Mapper { + return (value: string): string => { + return value + // anything `T::` to end up as `` + .replace(/T::/g, '') + // `system::` with `` - basically we find `` + .replace(/system::/g, '') + // replace `::` (possibly sanitiused just above) + .replace(/::/g, ''); + }; + } + + // remove wrapping values, i.e. Box -> Proposal + private _unwrap (check: string): Mapper { + return (value: string): string => { + let index = 0; + + while (index !== -1) { + index = value.indexOf(check); + + if (index !== -1) { + const start = index + check.length; + const end = this._findClosing(value, start); + + value = `${value.substr(start, end - start)}`; + } + } + + return value; + }; } } diff --git a/packages/api-codec/src/U128.ts b/packages/api-codec/src/U128.ts new file mode 100644 index 0000000000..3aec9a7cca --- /dev/null +++ b/packages/api-codec/src/U128.ts @@ -0,0 +1,13 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import BN from 'bn.js'; + +import CodecNumber from './codec/Number'; + +export default class U128 extends CodecNumber { + constructor (value?: CodecNumber | BN | string | number) { + super(value, 128); + } +} diff --git a/packages/api-codec/src/U16.ts b/packages/api-codec/src/U16.ts index c78a0594a8..6c16910280 100644 --- a/packages/api-codec/src/U16.ts +++ b/packages/api-codec/src/U16.ts @@ -4,10 +4,10 @@ import BN from 'bn.js'; -import CodecNumber from './base/Number'; +import CodecNumber from './codec/Number'; export default class U16 extends CodecNumber { - constructor (value?: BN | number) { + constructor (value?: CodecNumber | BN | string | number) { super(value, 16); } } diff --git a/packages/api-codec/src/U256.ts b/packages/api-codec/src/U256.ts new file mode 100644 index 0000000000..bbe765a387 --- /dev/null +++ b/packages/api-codec/src/U256.ts @@ -0,0 +1,13 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import BN from 'bn.js'; + +import CodecNumber from './codec/Number'; + +export default class U256 extends CodecNumber { + constructor (value?: CodecNumber | BN | string | number) { + super(value, 256); + } +} diff --git a/packages/api-codec/src/U32.ts b/packages/api-codec/src/U32.ts new file mode 100644 index 0000000000..3b99f1eff9 --- /dev/null +++ b/packages/api-codec/src/U32.ts @@ -0,0 +1,13 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import BN from 'bn.js'; + +import CodecNumber from './codec/Number'; + +export default class U32 extends CodecNumber { + constructor (value?: CodecNumber | BN | string | number) { + super(value, 32); + } +} diff --git a/packages/api-codec/src/U64.ts b/packages/api-codec/src/U64.ts new file mode 100644 index 0000000000..08c1e9dca8 --- /dev/null +++ b/packages/api-codec/src/U64.ts @@ -0,0 +1,13 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import BN from 'bn.js'; + +import CodecNumber from './codec/Number'; + +export default class U64 extends CodecNumber { + constructor (value?: CodecNumber | BN | string | number) { + super(value, 64); + } +} diff --git a/packages/api-codec/src/U8.ts b/packages/api-codec/src/U8.ts new file mode 100644 index 0000000000..7f21c6ab17 --- /dev/null +++ b/packages/api-codec/src/U8.ts @@ -0,0 +1,13 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import BN from 'bn.js'; + +import CodecNumber from './codec/Number'; + +export default class U8 extends CodecNumber { + constructor (value?: CodecNumber | BN | string | number) { + super(value, 8); + } +} diff --git a/packages/api-codec/src/VoteIndex.ts b/packages/api-codec/src/VoteIndex.ts new file mode 100644 index 0000000000..40f3212277 --- /dev/null +++ b/packages/api-codec/src/VoteIndex.ts @@ -0,0 +1,8 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import U32 from './U32'; + +export default class VoteIndex extends U32 { +} diff --git a/packages/api-codec/src/base/LengthCompact.spec.js b/packages/api-codec/src/base/LengthCompact.spec.js deleted file mode 100644 index f16d8c590d..0000000000 --- a/packages/api-codec/src/base/LengthCompact.spec.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017-2018 @polkadot/api-codec authors & contributors -// This software may be modified and distributed under the terms -// of the ISC license. See the LICENSE file for details. - -import LengthCompact from './LengthCompact'; - -describe('Compact', () => { - let compact; - - beforeEach(() => { - - }); - - // FIXME skipped since this one does not actually work as expected :() - // basically, bring in the tests since encoding with lengths are still - // proplematic (decoding at this point does work) - it.skip('encodes short u8', () => { - compact = new LengthCompact(78); - - expect( - compact.toU8a() - ).toEqual( - new Uint8Array([78 << 2]) - ); - }); -}); diff --git a/packages/api-codec/src/base/LengthCompact.ts b/packages/api-codec/src/base/LengthCompact.ts deleted file mode 100644 index 425609f60a..0000000000 --- a/packages/api-codec/src/base/LengthCompact.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2017-2018 @polkadot/api-codec authors & contributors -// This software may be modified and distributed under the terms -// of the ISC license. See the LICENSE file for details. - -import BN from 'bn.js'; -import bnToU8a from '@polkadot/util/bn/toU8a'; -import u8aConcat from '@polkadot/util/u8a/concat'; -import u8aToBn from '@polkadot/util/u8a/toBn'; - -import CodecBaseLength from './LengthFixed'; - -const MAX_VAL_U8 = new BN(2).pow(new BN(8 - 2)).subn(1); -const MAX_VAL_U16 = new BN(2).pow(new BN(16 - 2)).subn(1); -const MAX_VAL_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 -// -// 0b00 00 00 00 / 00 00 00 00 / 00 00 00 00 / 00 00 00 00 -// (0 ... 2**6 - 1) (u8) -// xx xx xx 00 -// (2**6 ... 2**14 - 1) (u8, u16) low LH high -// yL yL yL 01 / yH yH yH yL -// (2**14 ... 2**30 - 1) (u16, u32) low LMMH high -// zL zL zL 10 / zM zM zM zL / zM zM zM zM / zH zH zH zM -// (2**30 ... 2**536 - 1) (u32, u64, u128, U256, U512, U520) straight LE-encoded -// nn nn nn 11 [ / zz zz zz zz ]{4 + n} -// -// Note: we use *LOW BITS* of the LSB in LE encoding to encode the 2 bit key. -export default class CodecLengthCompact extends CodecBaseLength { - byteLength (): number { - return this.toU8a().length; - } - - fromU8a (input: Uint8Array): CodecLengthCompact { - const flag = input[0] & 0b11; - - if (flag === 0b00) { - this.raw = new BN(input[0]).shrn(2); - } else if (flag === 0b01) { - this.raw = u8aToBn(input.slice(0, 2), true).shrn(2); - } else if (flag === 0b10) { - this.raw = u8aToBn(input.slice(0, 4), true).shrn(2); - } else { - this.raw = u8aToBn(input.subarray(1, 5), true); - } - - return this; - } - - toU8a (): Uint8Array { - if (this.raw.lte(MAX_VAL_U8)) { - return new Uint8Array([this.raw.toNumber() << 2]); - } else if (this.raw.lte(MAX_VAL_U16)) { - const u8a = bnToU8a(this.raw, 16, true); - - u8a.set([ - (u8a[0] << 2) | 0b01 - ]); - - return u8a; - } else if (this.raw.lte(MAX_VAL_U32)) { - const u8a = bnToU8a(this.raw, 32, true); - - u8a.set([ - (u8a[0] << 2) | 0b10 - ]); - - return u8a; - } - - return u8aConcat( - new Uint8Array([ - 0b11 - ]), - bnToU8a(this.raw, 32, true) - ); - } -} diff --git a/packages/api-codec/src/base/LengthFixed.ts b/packages/api-codec/src/base/LengthFixed.ts deleted file mode 100644 index 86aa8fecbf..0000000000 --- a/packages/api-codec/src/base/LengthFixed.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2017-2018 @polkadot/api-codec authors & contributors -// This software may be modified and distributed under the terms -// of the ISC license. See the LICENSE file for details. - -import BN from 'bn.js'; -import bnToBn from '@polkadot/util/bn/toBn'; -import bnToU8a from '@polkadot/util/bn/toU8a'; -import u8aToBn from '@polkadot/util/u8a/toBn'; - -import CodecBase from './Base'; - -// A basic u32 LE length-encoder. It is basically used in Vectors, Arrays and String -// (anything variable) to do the encoding/decoding for the length prefixes. (It has -// been superceded in use by the compact encoder, i.e. LengthCompact) -export default class CodecLengthFixed extends CodecBase { - constructor (value: BN | number = new BN(0)) { - super( - bnToBn(value) - ); - } - - byteLength (): number { - return 4; - } - - fromJSON (): CodecLengthFixed { - throw new Error('CodecLength::fromJSON: unimplemented'); - } - - fromNumber (value: BN | number): CodecLengthFixed { - this.raw = bnToBn(value); - - return this; - } - - fromU8a (input: Uint8Array): CodecLengthFixed { - this.raw = u8aToBn(input.subarray(0, 4), true); - - return this; - } - - toJSON (): any { - throw new Error('CodecLength::toJSON: unimplemented'); - } - - toNumber (): number { - return this.raw.toNumber(); - } - - toString (): string { - throw new Error('CodecLength::toString: unimplemented'); - } - - toU8a (): Uint8Array { - return bnToU8a(this.raw, 32, true); - } - - setValue (value: BN | number): void { - this.raw = bnToBn(value); - } -} diff --git a/packages/api-codec/src/base/Array.ts b/packages/api-codec/src/codec/Array.ts similarity index 98% rename from packages/api-codec/src/base/Array.ts rename to packages/api-codec/src/codec/Array.ts index 9f7194ad11..9ab23a684d 100644 --- a/packages/api-codec/src/base/Array.ts +++ b/packages/api-codec/src/codec/Array.ts @@ -5,7 +5,7 @@ import u8aConcat from '@polkadot/util/u8a/concat'; import CodecBase from './Base'; -import Length from './LengthCompact'; +import Length from './Length'; // This manages codec arrays. Intrernally it keeps track of the length (as decoded) and allows // construction with the passed `Type` in the constructor. It aims to be an array-like structure, diff --git a/packages/api-codec/src/base/Base.ts b/packages/api-codec/src/codec/Base.ts similarity index 100% rename from packages/api-codec/src/base/Base.ts rename to packages/api-codec/src/codec/Base.ts diff --git a/packages/api-codec/src/codec/Bytes.ts b/packages/api-codec/src/codec/Bytes.ts new file mode 100644 index 0000000000..30103b4409 --- /dev/null +++ b/packages/api-codec/src/codec/Bytes.ts @@ -0,0 +1,56 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import u8aConcat from '@polkadot/util/u8a/concat'; + +import CodecU8a from './U8a'; +import Length from './Length'; + +// A CodecBytes. The significant difference between this and a normal Uint8Array is that +// this version allows for length-encoding. (i.e. it is a variable-item codec, the same +// as what is found in String and Array) +export default class CodecBytes extends CodecU8a { + protected _length: Length; + + constructor (value: CodecU8a | Uint8Array = new Uint8Array()) { + super( + value instanceof CodecU8a + ? value.raw + : value + ); + + this._length = new Length(value.length); + } + + byteLength (): number { + return this._length.byteLength() + + this._length.toNumber(); + } + + fromJSON (input: any): CodecBytes { + super.fromJSON(input); + + this._length.setValue(this.raw.length); + + return this; + } + + fromU8a (input: Uint8Array): CodecBytes { + this._length.fromU8a(input); + + const length = this._length.toNumber(); + const offset = this._length.byteLength(); + + super.fromU8a(input.subarray(offset, offset + length)); + + return this; + } + + toU8a (): Uint8Array { + return u8aConcat( + this._length.toU8a(), + this.raw + ); + } +} diff --git a/packages/api-codec/src/base/Enum.ts b/packages/api-codec/src/codec/Enum.ts similarity index 100% rename from packages/api-codec/src/base/Enum.ts rename to packages/api-codec/src/codec/Enum.ts diff --git a/packages/api-codec/src/base/EnumType.ts b/packages/api-codec/src/codec/EnumType.ts similarity index 100% rename from packages/api-codec/src/base/EnumType.ts rename to packages/api-codec/src/codec/EnumType.ts diff --git a/packages/api-codec/src/codec/Length.spec.js b/packages/api-codec/src/codec/Length.spec.js new file mode 100644 index 0000000000..c2abeaeca0 --- /dev/null +++ b/packages/api-codec/src/codec/Length.spec.js @@ -0,0 +1,77 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import Length from './Length'; + +describe('Compact', () => { + it('encodes short u8', () => { + expect( + new Length(18).toU8a() + ).toEqual( + new Uint8Array([18 << 2]) + ); + }); + + it('encodes max u8 values', () => { + expect( + new Length(63).toU8a() + ).toEqual( + new Uint8Array([0b11111100]) + ); + }); + + it('encodes basic u16 value', () => { + expect( + new Length(511).toU8a() + ).toEqual( + new Uint8Array([0b11111101, 0b00000111]) + ); + }); + + it('decodes from same u16 encoded value', () => { + expect( + new Length() + .fromU8a(new Uint8Array([0b11111101, 0b00000111])) + .toNumber() + ).toEqual( + 511 + ); + }); + + it('encodes basic u32 values (short)', () => { + expect( + new Length(0xffff).toU8a() + ).toEqual( + new Uint8Array([254, 255, 3, 0]) + ); + }); + + it('decodes from same u32 encoded value (short)', () => { + expect( + new Length() + .fromU8a(new Uint8Array([254, 255, 3, 0])) + .toNumber() + ).toEqual( + 0xffff + ); + }); + + it('encodes basic u32 values (full)', () => { + expect( + new Length(0xfffffff9).toU8a() + ).toEqual( + new Uint8Array([3, 249, 255, 255, 255]) + ); + }); + + it('decodes from same u32 encoded value (full)', () => { + expect( + new Length() + .fromU8a(new Uint8Array([3, 249, 255, 255, 255])) + .toNumber() + ).toEqual( + 0xfffffff9 + ); + }); +}); diff --git a/packages/api-codec/src/codec/Length.ts b/packages/api-codec/src/codec/Length.ts new file mode 100644 index 0000000000..36ea200678 --- /dev/null +++ b/packages/api-codec/src/codec/Length.ts @@ -0,0 +1,115 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import BN from 'bn.js'; +import bnToBn from '@polkadot/util/bn/toBn'; +import bnToU8a from '@polkadot/util/bn/toU8a'; +import u8aConcat from '@polkadot/util/u8a/concat'; +import u8aToBn from '@polkadot/util/u8a/toBn'; + +import CodecBase from './Base'; + +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 +// +// 0b00 00 00 00 / 00 00 00 00 / 00 00 00 00 / 00 00 00 00 +// (0 ... 2**6 - 1) (u8) +// xx xx xx 00 +// (2**6 ... 2**14 - 1) (u8, u16) low LH high +// yL yL yL 01 / yH yH yH yL +// (2**14 ... 2**30 - 1) (u16, u32) low LMMH high +// zL zL zL 10 / zM zM zM zL / zM zM zM zM / zH zH zH zM +// (2**30 ... 2**536 - 1) (u32, u64, u128, U256, U512, U520) straight LE-encoded +// nn nn nn 11 [ / zz zz zz zz ]{4 + n} +// +// Note: we use *LOW BITS* of the LSB in LE encoding to encode the 2 bit key. +export default class CodecLength extends CodecBase { + constructor (value: CodecLength | BN | number = new BN(0)) { + super( + value instanceof CodecLength + ? value.raw + : bnToBn(value) + ); + } + + static decode (input: Uint8Array): BN { + const flag = input[0] & 0b11; + + if (flag === 0b00) { + return new BN(input[0]).shrn(2); + } else if (flag === 0b01) { + return u8aToBn(input.slice(0, 2), true).shrn(2); + } else if (flag === 0b10) { + return u8aToBn(input.slice(0, 4), true).shrn(2); + } + + return u8aToBn(input.subarray(1, 5), true); + } + + static encode (length: BN): Uint8Array { + if (length.lte(MAX_U8)) { + return new Uint8Array([length.toNumber() << 2]); + } else if (length.lte(MAX_U16)) { + return bnToU8a(length.shln(2).addn(0b01), 16, true); + } else if (length.lte(MAX_U32)) { + return bnToU8a(length.shln(2).addn(0b10), 32, true); + } + + return u8aConcat( + new Uint8Array([ + 0b11 + ]), + bnToU8a(length, 32, true) + ); + } + + get length (): number { + return this.raw.toNumber(); + } + + byteLength (): number { + return this.toU8a().length; + } + + fromJSON (): CodecLength { + throw new Error('CodecLength::fromJSON: unimplemented'); + } + + fromNumber (value: BN | number): CodecLength { + this.raw = bnToBn(value); + + return this; + } + + fromU8a (input: Uint8Array): CodecLength { + this.raw = CodecLength.decode(input); + + return this; + } + + toJSON (): any { + throw new Error('CodecLength::toJSON: unimplemented'); + } + + toNumber (): number { + return this.raw.toNumber(); + } + + toString (): string { + throw new Error('CodecLength::toString: unimplemented'); + } + + toU8a (): Uint8Array { + return CodecLength.encode(this.raw); + } + + setValue (value: BN | number): void { + this.raw = bnToBn(value); + } +} diff --git a/packages/api-codec/src/base/Number.ts b/packages/api-codec/src/codec/Number.ts similarity index 73% rename from packages/api-codec/src/base/Number.ts rename to packages/api-codec/src/codec/Number.ts index 1889a61236..78c66271c0 100644 --- a/packages/api-codec/src/base/Number.ts +++ b/packages/api-codec/src/codec/Number.ts @@ -4,6 +4,7 @@ import BN from 'bn.js'; import isHex from '@polkadot/util/is/hex'; +import isString from '@polkadot/util/is/string'; import bnToBn from '@polkadot/util/bn/toBn'; import bnToHex from '@polkadot/util/bn/toHex'; import bnToU8a from '@polkadot/util/bn/toU8a'; @@ -12,9 +13,7 @@ import u8aToBn from '@polkadot/util/u8a/toBn'; import CodecBase from './Base'; -type BitLength = 8 | 16 | 32 | 64 | 128; - -const DEFAULT_VALUE = new BN(0); +type BitLength = 8 | 16 | 32 | 64 | 128 | 256; // A generic number codec. For Substrate all numbers are LE encoded, this handles the encoding // and decoding of those numbers. Upon construction the bitLength is provided and any additional @@ -25,22 +24,32 @@ const DEFAULT_VALUE = new BN(0); export default class CodecNumber extends CodecBase { private _bitLength: BitLength; - constructor (value: BN | number = DEFAULT_VALUE, bitLength: BitLength = 64) { + constructor (value: CodecNumber | BN | string | number = 0, bitLength: BitLength = 64) { super( - bnToBn(value) + CodecNumber.decode(value) ); this._bitLength = bitLength; } + static decode (value: CodecNumber | BN | string | number): BN { + if (value instanceof CodecNumber) { + return value.raw; + } else if (isHex(value)) { + return hexToBn(value as string); + } else if (isString(value)) { + return new BN(value, 10); + } + + return bnToBn(value); + } + byteLength (): number { return this._bitLength / 8; } fromJSON (input: any): CodecNumber { - this.raw = isHex(input) - ? hexToBn(input) - : new BN(input); + this.raw = CodecNumber.decode(input); return this; } diff --git a/packages/api-codec/src/base/Option.ts b/packages/api-codec/src/codec/Option.ts similarity index 100% rename from packages/api-codec/src/base/Option.ts rename to packages/api-codec/src/codec/Option.ts diff --git a/packages/api-codec/src/base/Struct.ts b/packages/api-codec/src/codec/Struct.ts similarity index 100% rename from packages/api-codec/src/base/Struct.ts rename to packages/api-codec/src/codec/Struct.ts diff --git a/packages/api-codec/src/codec/U8a.ts b/packages/api-codec/src/codec/U8a.ts new file mode 100644 index 0000000000..dae2020904 --- /dev/null +++ b/packages/api-codec/src/codec/U8a.ts @@ -0,0 +1,58 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import u8aToHex from '@polkadot/util/u8a/toHex'; +import toU8a from '@polkadot/util/u8a/toU8a'; + +import CodecBase from './Base'; + +// A CodecU8a. A basic wrapper around Uint8Array, with no frills and no fuss. It +// wraps a Uint8Array. It does differ from other implementations wher it will +// consume the full u8a as passed to it in fromU8a. As such it is meant to be +// subclassed where the wrapper takes care of the actual lengths. +export default class CodecU8a extends CodecBase { + constructor (value: CodecU8a | string | Uint8Array = new Uint8Array()) { + super( + value instanceof CodecU8a + ? value.raw + : toU8a(value) + ); + } + + get length (): number { + return this.byteLength(); + } + + byteLength (): number { + return this.raw.length; + } + + fromJSON (input: any): CodecU8a { + this.raw = toU8a(input); + + return this; + } + + fromU8a (input: Uint8Array): CodecU8a { + this.raw = input; + + return this; + } + + toHex (): string { + return u8aToHex(this.raw); + } + + toJSON (): any { + return this.toHex(); + } + + toU8a (): Uint8Array { + return this.raw; + } + + toString (): string { + return this.toHex(); + } +} diff --git a/packages/api-codec/src/codec/U8aFixed.ts b/packages/api-codec/src/codec/U8aFixed.ts new file mode 100644 index 0000000000..b8fe459ad9 --- /dev/null +++ b/packages/api-codec/src/codec/U8aFixed.ts @@ -0,0 +1,29 @@ +// Copyright 2017-2018 @polkadot/api-codec authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import CodecU8a from './U8a'; + +type BitLength = 256 | 512; + +// A U8a that manages a a sequence of bytes up to the specified bitLength. Not meant +// to be used directly, rather is should be subclassed with the specific lengths. +export default class CodecU8aFixed extends CodecU8a { + protected _bitLength: number; + + constructor (value: CodecU8a | string | Uint8Array = new Uint8Array(), bitLength: BitLength = 256) { + super(value); + + this._bitLength = bitLength; + } + + byteLength (): number { + return this._bitLength / 8; + } + + fromU8a (input: Uint8Array): CodecU8aFixed { + super.fromU8a(input.subarray(0, this.byteLength())); + + return this; + } +} diff --git a/packages/api-format/src/output.ts b/packages/api-format/src/output.ts index 0278af5162..a94a0f8205 100644 --- a/packages/api-format/src/output.ts +++ b/packages/api-format/src/output.ts @@ -26,9 +26,7 @@ const metaDecode = (input: Array) => { const metadata = new Metadata(); try { - metadata.fromU8a( - Uint8Array.from(input) - ); + metadata.fromJSON(input); } catch (error) { console.error('current', JSON.stringify(metadata.toJSON()), error);