diff --git a/packages/api-codec/src/AccountId.ts b/packages/api-codec/src/AccountId.ts index 914283fae8..1110fe895c 100644 --- a/packages/api-codec/src/AccountId.ts +++ b/packages/api-codec/src/AccountId.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from './types'; + import encodeAddress from '@polkadot/util-keyring/address/encode'; import decodeAddress from '@polkadot/util-keyring/address/decode'; import hexToU8a from '@polkadot/util/hex/toU8a'; @@ -14,9 +16,9 @@ import U8aFixed from './codec/U8aFixed'; // A wrapper around an AccountId/PublicKey representation. Since we are dealing with // underlying PublicKeys (32 bytes in length), we extend from U8aFixed which is -// basically just a Uint8Array wrapper with a fixed length. +// just a Uint8Array wrapper with a fixed length. export default class AccountId extends U8aFixed { - constructor (value: U8a | string | Uint8Array = new Uint8Array()) { + constructor (value: AnyU8a = new Uint8Array()) { super( value instanceof U8a ? value.raw diff --git a/packages/api-codec/src/AccountIndex.ts b/packages/api-codec/src/AccountIndex.ts index 11ec565d1f..a34f1a8365 100644 --- a/packages/api-codec/src/AccountIndex.ts +++ b/packages/api-codec/src/AccountIndex.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from './types'; + import u8aToHex from '@polkadot/util/u8a/toHex'; import u8aToU8a from '@polkadot/util/u8a/toU8a'; @@ -11,7 +13,7 @@ import U8a from './codec/U8a'; // for an Account. We extends from U8a which is basically // just a Uint8Array wrapper. export default class AccountIndex extends U8a { - constructor (value: U8a | string | Uint8Array = new Uint8Array()) { + constructor (value: AnyU8a = new Uint8Array()) { super( value instanceof U8a ? value.raw diff --git a/packages/api-codec/src/Address.spec.js b/packages/api-codec/src/Address.spec.js index 112f386e9b..b1a2c9d87d 100644 --- a/packages/api-codec/src/Address.spec.js +++ b/packages/api-codec/src/Address.spec.js @@ -33,6 +33,20 @@ describe('Address', () => { ); }); + it('encodes address to ss-58 format', () => { + 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('decodes with a prefix (1-byte)', () => { expect( new Address() diff --git a/packages/api-codec/src/Address.ts b/packages/api-codec/src/Address.ts index 57494d963d..986f2c4ddb 100644 --- a/packages/api-codec/src/Address.ts +++ b/packages/api-codec/src/Address.ts @@ -93,6 +93,11 @@ export default class Address extends Base { return this; } + // FIXME I actually believe this is wrong, it needs to be checked. Here 1-byte + // addresses are actually 2 bytes, 2-byte is 3-bytes, etc. I believe the actual + // short-encoding should be left completely inside AccountId (For now, leaving + // as-is until we can actually pull storage data and check - and/or read the + // actual code again to check the implementation) fromU8a (input: Uint8Array): Address { this.raw = Address.readLength(input) === 32 ? new AccountId().fromU8a(input.subarray(1)) diff --git a/packages/api-codec/src/AuthorityId.ts b/packages/api-codec/src/AuthorityId.ts new file mode 100644 index 0000000000..51a438c24f --- /dev/null +++ b/packages/api-codec/src/AuthorityId.ts @@ -0,0 +1,11 @@ +// 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'; + +// Wrapper for a AuthorityId. Same as an normal AccountId, i.e. a wrapper +// around publicKey, however specialized since it specifically points to +// an authority. +export default class AuthorityId extends AccountId { +} diff --git a/packages/api-codec/src/Bft.spec.js b/packages/api-codec/src/Bft.spec.js new file mode 100644 index 0000000000..03ec07bb26 --- /dev/null +++ b/packages/api-codec/src/Bft.spec.js @@ -0,0 +1,60 @@ +// 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 { BftAuthoritySignature, BftHashSignature, Justification } from './Bft'; + +describe('BftAuthoritySignature', () => { + const sig = new BftAuthoritySignature({ + authorityId: '0x12344321', + signature: '0x567890098765' + }); + + it('has the correct authorityId', () => { + expect(sig.authorityId.toHex()).toEqual('0x12344321'); + }); + + it('has the correct signature', () => { + expect(sig.signature.toHex()).toEqual('0x567890098765'); + }); +}); + +describe('BftHashSignature', () => { + const sig = new BftHashSignature({ + hash: '0x12344321', + signature: '0x567890098765' + }); + + it('has the correct hash', () => { + expect(sig.hash.toHex()).toEqual('0x12344321'); + }); + + it('has the correct signature', () => { + expect(sig.signature.toHex()).toEqual('0x567890098765'); + }); +}); + +describe('Justification', () => { + const just = new Justification({ + round_number: 32, + hash: '0xabcd', + signatures: [ + { authorityId: '0x1234', signature: '0x5678' }, + { authorityId: '0x9876', signature: '0x5432' } + ] + }); + + it('has the correct hash', () => { + expect(just.hash.toHex()).toEqual('0xabcd'); + }); + + it('has the correct round', () => { + expect(just.round.toNumber()).toEqual(32); + }); + + it('has the correct signatures', () => { + const sig = just.signatures.at(1); + + expect(sig.authorityId.toHex()).toEqual('0x9876'); + }); +}); diff --git a/packages/api-codec/src/Bft.ts b/packages/api-codec/src/Bft.ts new file mode 100644 index 0000000000..d8c73fb9b9 --- /dev/null +++ b/packages/api-codec/src/Bft.ts @@ -0,0 +1,90 @@ +// 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 { AnyNumber, AnyU8a } from './types'; + +import Struct from './codec/Struct'; +import Vector from './codec/Vector'; +import AuthorityId from './AuthorityId'; +import Hash from './Hash'; +import Signature from './Signature'; +import U32 from './U32'; + +export type BftAuthoritySignatureValue = { + authorityId?: AnyU8a, + signature?: AnyU8a +}; + +// Represents a Bft Hash and Signature pairing, typically used in reporting +// network behaviour. +export class BftAuthoritySignature extends Struct { + constructor (value: BftAuthoritySignatureValue = {}) { + super({ + authorityId: AuthorityId, + signature: Signature + }, value); + } + + get authorityId (): AuthorityId { + return this.raw.authorityId as AuthorityId; + } + + get signature (): Signature { + return this.raw.signature as Signature; + } +} + +export type BftHashSignatureValue = { + hash?: AnyU8a, + signature?: AnyU8a +}; + +// Represents a Bft Hash and Signature pairing, typically used in reporting +// network behaviour. +export class BftHashSignature extends Struct { + constructor (value: BftHashSignatureValue = {}) { + super({ + hash: Hash, + signature: Signature + }, value); + } + + get hash (): Hash { + return this.raw.hash as Hash; + } + + get signature (): Signature { + return this.raw.signature as Signature; + } +} + +export type JustificationValue = { + round_number?: AnyNumber, + hash?: AnyU8a, + signatures?: Array +}; + +export class Justification extends Struct { + constructor (value: JustificationValue = {}) { + super({ + // FIXME Rust returns this as "round_number", we actually want a JSON alias + // in the structure to take care of these renames... + round_number: U32, + hash: Hash, + signatures: Vector.with(BftAuthoritySignature) + }, value); + } + + get hash (): Hash { + return this.raw.hash as Hash; + } + + get round (): U32 { + return this.raw.round_number as U32; + } + + get signatures (): Vector { + return this.raw.signatures as Vector; + } +} diff --git a/packages/api-codec/src/Block.spec.js b/packages/api-codec/src/Block.spec.js index 26275324f9..295631ced5 100644 --- a/packages/api-codec/src/Block.spec.js +++ b/packages/api-codec/src/Block.spec.js @@ -48,4 +48,25 @@ describe('Block', () => { block.extrinsics.at(0).length ).toEqual(111); // eslint-disable-line }); + + // FIXME check again when we have a valid chain/UI + it.skip('has a valid block hash', () => { + expect( + new Block({ + extrinsics: [ + [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 139, 165, 170, 91, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ], + header: { + digest: { + logs: [] + }, + extrinsicsRoot: '0x5ce1a2c55efaf371f06fd94672779daf130591a12f7513ae786bea4fa7bd499e', + number: 1556355, + parentHash: '0x09223919f63b5ded0c7bf7d953ba22bf30ea8a19e6be4de35f25163b2b268490', + stateRoot: '0xd45159e04f36955ecb9c73d6ca514ac2d0e3ce00f58588b7c142d36cf7d237ec' + } + }).hash.toHex() + ).toEqual('0xd1b7e2c8f1ba2665d89dba334dcf45caa12e34d22587a09e2d03372366a81d8b'); + }); }); diff --git a/packages/api-codec/src/Block.ts b/packages/api-codec/src/Block.ts index 92d8c0f99c..b491d0efbb 100644 --- a/packages/api-codec/src/Block.ts +++ b/packages/api-codec/src/Block.ts @@ -2,15 +2,24 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from './types'; + +import blake2Asu8a from '@polkadot/util-crypto/blake2/asU8a'; + import Struct from './codec/Struct'; import Vector from './codec/Vector'; - import Extrinsic from './Extrinsic'; -import Header from './Header'; +import Hash from './Hash'; +import Header, { HeaderValue } from './Header'; + +export type BlockValue = { + extrinsics?: Array + header?: HeaderValue +}; // A block encoded with header and extrinsics export default class Block extends Struct { - constructor (value?: any) { + constructor (value: BlockValue = {}) { super({ header: Header, extrinsics: Vector.with(Extrinsic) @@ -21,6 +30,13 @@ export default class Block extends Struct { return this.raw.extrinsics as Vector; } + // convenience, encodes the header and returns the actual hash + get hash (): Hash { + return new Hash( + blake2Asu8a(this.toU8a(), 256) + ); + } + get header (): Header { return this.raw.header as Header; } diff --git a/packages/api-codec/src/Bytes.ts b/packages/api-codec/src/Bytes.ts index de3405a9b5..f77c86fb8e 100644 --- a/packages/api-codec/src/Bytes.ts +++ b/packages/api-codec/src/Bytes.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from './types'; + import u8aConcat from '@polkadot/util/u8a/concat'; import Length from './codec/Length'; @@ -13,7 +15,7 @@ import U8a from './codec/U8a'; export default class Bytes extends U8a { protected _length: Length; - constructor (value?: U8a | string | Uint8Array) { + constructor (value?: AnyU8a) { super(value); this._length = new Length(this.raw.length); diff --git a/packages/api-codec/src/H256.ts b/packages/api-codec/src/H256.ts index ab53409119..bb5604341c 100644 --- a/packages/api-codec/src/H256.ts +++ b/packages/api-codec/src/H256.ts @@ -2,13 +2,14 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. -import U8a from './codec/U8a'; +import { AnyU8a } from './types'; + import U8aFixed 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 U8aFixed { - constructor (value?: U8a | string | Uint8Array) { + constructor (value?: AnyU8a) { super(value, 256); } } diff --git a/packages/api-codec/src/H512.ts b/packages/api-codec/src/H512.ts index 4c12b7c3d6..4b00d4c57c 100644 --- a/packages/api-codec/src/H512.ts +++ b/packages/api-codec/src/H512.ts @@ -2,12 +2,13 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. -import U8a from './codec/U8a'; +import { AnyU8a } from './types'; + import U8aFixed from './codec/U8aFixed'; // Hash containing 512 bits (64 bytes), typically used for signatures export default class H512 extends U8aFixed { - constructor (value?: U8a | string | Uint8Array) { + constructor (value?: AnyU8a) { super(value, 512); } } diff --git a/packages/api-codec/src/Header.spec.js b/packages/api-codec/src/Header.spec.js index 4384c3eebd..c5da72112a 100644 --- a/packages/api-codec/src/Header.spec.js +++ b/packages/api-codec/src/Header.spec.js @@ -27,4 +27,19 @@ describe('Header', () => { header.digest.logs.toString() ).toEqual('[]'); }); + + // FIXME check again when we have a valid chain/UI + it.skip('creates actual valid hash', () => { + expect( + new Header({ + digest: { + logs: [] + }, + extrinsicsRoot: '0x5ce1a2c55efaf371f06fd94672779daf130591a12f7513ae786bea4fa7bd499e', + number: 1556355, + parentHash: '0x09223919f63b5ded0c7bf7d953ba22bf30ea8a19e6be4de35f25163b2b268490', + stateRoot: '0xd45159e04f36955ecb9c73d6ca514ac2d0e3ce00f58588b7c142d36cf7d237ec' + }).hash.toHex() + ).toEqual('0x3a91467e3d298684c2d3ee68362615e9b21fa9e37739c02c25f8075918e1ab11'); + }); }); diff --git a/packages/api-codec/src/Header.ts b/packages/api-codec/src/Header.ts index b9d2f063c1..1c5b2e0ed9 100644 --- a/packages/api-codec/src/Header.ts +++ b/packages/api-codec/src/Header.ts @@ -2,10 +2,10 @@ // 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 { AnyNumber, AnyU8a } from './types'; + import blake2Asu8a from '@polkadot/util-crypto/blake2/asU8a'; -import UInt from './codec/UInt'; import Struct from './codec/Struct'; import Vector from './codec/Vector'; @@ -13,21 +13,21 @@ import BlockNumber from './BlockNumber'; import Bytes from './Bytes'; import Hash from './Hash'; -type DigestStruct = { - logs?: Array +type DigestValue = { + logs?: Array }; -type HeaderStruct = { - digest?: DigestStruct, - extrinsicsRoot?: Hash | Uint8Array | string, - number?: UInt | BN | number | string, - parentHash?: Hash | Uint8Array | string, - stateRoot?: Hash | Uint8Array | string +export type HeaderValue = { + digest?: DigestValue, + extrinsicsRoot?: AnyU8a, + number?: AnyNumber, + parentHash?: AnyU8a, + stateRoot?: AnyU8a }; // A block header digest. export class Digest extends Struct { - constructor (value: DigestStruct = {}) { + constructor (value: DigestValue = {}) { super({ logs: Vector.with(Bytes) }, value); @@ -40,7 +40,7 @@ export class Digest extends Struct { // A block header. export default class Header extends Struct { - constructor (value: HeaderStruct = {}) { + constructor (value: HeaderValue = {}) { super({ parentHash: Hash, number: BlockNumber, @@ -62,7 +62,7 @@ export default class Header extends Struct { return this.raw.extrinsicsRoot as Hash; } - // convernience, encodes the header and returns the actual hash + // convenience, encodes the header and returns the actual hash get hash (): Hash { return new Hash( blake2Asu8a(this.toU8a(), 256) diff --git a/packages/api-codec/src/KeyValue.ts b/packages/api-codec/src/KeyValue.ts index 9f2d14883a..785c9ec165 100644 --- a/packages/api-codec/src/KeyValue.ts +++ b/packages/api-codec/src/KeyValue.ts @@ -2,13 +2,15 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from './types'; + import Struct from './codec/Struct'; import Bytes from './Bytes'; -type KeyValueStruct = { - key?: Uint8Array | string, - value?: Uint8Array | string +type KeyValueValue = { + key?: AnyU8a, + value?: AnyU8a }; // KeyValue structure. Since most of the keys and resultant values in Subtrate is @@ -16,7 +18,7 @@ type KeyValueStruct = { // 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 Struct { - constructor (value: KeyValueStruct = {}) { + constructor (value: KeyValueValue = {}) { super({ key: Bytes, value: Bytes diff --git a/packages/api-codec/src/Metadata.ts b/packages/api-codec/src/Metadata.ts index eba07b54b6..eea3c3b00b 100644 --- a/packages/api-codec/src/Metadata.ts +++ b/packages/api-codec/src/Metadata.ts @@ -174,11 +174,14 @@ export class StorageFunctionType$Map extends Struct { } export class StorageFunctionType extends EnumType { - constructor () { + // NOTE Since this is called dynamically, we may have empty values here + constructor (index?: number, value?: any) { super([ Type, StorageFunctionType$Map ], ['Plain', 'Map']); + + this.setValue(index, value); } get isMap (): boolean { diff --git a/packages/api-codec/src/MisbehaviorReport.spec.js b/packages/api-codec/src/MisbehaviorReport.spec.js new file mode 100644 index 0000000000..8f3322310d --- /dev/null +++ b/packages/api-codec/src/MisbehaviorReport.spec.js @@ -0,0 +1,53 @@ +// 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 MisbehaviorReport, { BftAtReport } from './MisbehaviorReport'; + +describe('BftAtReport', () => { + const report = new BftAtReport({ + round: 16, + a: { + hash: '0x1234', + signature: '0x5678' + }, + b: { + hash: '0x8765', + signature: '0x4321' + } + }); + + it('has the correct round', () => { + expect(report.round.toNumber()).toEqual(16); + }); + + it('has the correct hash (a)', () => { + expect(report.a.hash.toHex()).toEqual('0x1234'); + }); + + it('has the correct signature (b)', () => { + expect(report.b.signature.toHex()).toEqual('0x4321'); + }); +}); + +describe('MisbehaviorReport', () => { + const report = new MisbehaviorReport({ + parentHash: '0x01020304', + parentNumber: 78, + target: '0x11112222', + misbehavior: 0x12 + }); + + it('has the correct misbehavior type', () => { + expect(report.misbehavior.Type).toEqual('BftDoubleCommit'); + }); + + it('has the correct parent block', () => { + expect(report.parentHash.toHex()).toEqual('0x01020304'); + expect(report.parentNumber.toNumber()).toEqual(78); + }); + + it('identifies the misbehaving authority', () => { + expect(report.target.toHex()).toEqual('0x11112222'); + }); +}); diff --git a/packages/api-codec/src/MisbehaviorReport.ts b/packages/api-codec/src/MisbehaviorReport.ts new file mode 100644 index 0000000000..dde4dca845 --- /dev/null +++ b/packages/api-codec/src/MisbehaviorReport.ts @@ -0,0 +1,99 @@ +// 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 { AnyNumber } from './types'; + +import EnumType from './codec/EnumType'; +import Struct from './codec/Struct'; +import AuthorityId from './AuthorityId'; +import { BftHashSignature, BftHashSignatureValue } from './Bft'; +import BlockNumber from './BlockNumber'; +import Hash from './Hash'; +import U32 from './U32'; + +type BftAtReportValue = { + round?: AnyNumber, + a?: BftHashSignatureValue, + b?: BftHashSignatureValue +}; + +// A report of a/b hash-signature pairs for a specific index. This is the same +// structure as is used in BftDoublePrepare & BftDoubleCommit +// +// FIXME It is not entirely obvious from the actual Rust code what the specific +// items in the structure is called, except a & b (one should be expected, the +// other actual) +export class BftAtReport extends Struct { + constructor (value: BftAtReportValue = {}) { + super({ + round: U32, + a: BftHashSignature, + b: BftHashSignature + }, value); + } + + get a (): BftHashSignature { + return this.raw.a as BftHashSignature; + } + + get b (): BftHashSignature { + return this.raw.b as BftHashSignature; + } + + get round (): U32 { + return this.raw.round as U32; + } +} + +// Report of a double-prepare +export class BftDoublePrepare extends BftAtReport { +} + +// Report of a double-commit +export class BftDoubleCommit extends BftAtReport { +} + +export class MisbehaviorKind extends EnumType { + constructor (index: number, value: BftAtReportValue = {}) { + super([ + BftDoublePrepare, + BftDoubleCommit + ], [], [0x11, 0x12]); + + this.setValue(index, value); + } +} + +type MisbehaviorReportValue = { + unstakeThreshold?: AnyNumber, + validatorPayment?: AnyNumber +}; + +// A Misbehaviour report against a specific AuthorityId +export default class MisbehaviorReport extends Struct { + constructor (value: MisbehaviorReportValue = {}) { + super({ + parentHash: Hash, + parentNumber: BlockNumber, + target: AuthorityId, + misbehavior: MisbehaviorKind + }, value); + } + + get misbehavior (): MisbehaviorKind { + return this.raw.misbehavior as MisbehaviorKind; + } + + get parentHash (): Hash { + return this.raw.parentHash as Hash; + } + + get parentNumber (): BlockNumber { + return this.raw.parentNumber as BlockNumber; + } + + get target (): AuthorityId { + return this.raw.target as AuthorityId; + } +} diff --git a/packages/api-codec/src/SignedBlock.rpc.json b/packages/api-codec/src/SignedBlock.rpc.json new file mode 100644 index 0000000000..ea5e44d6b9 --- /dev/null +++ b/packages/api-codec/src/SignedBlock.rpc.json @@ -0,0 +1 @@ +{"jsonrpc":"2.0","result":{"block":{"extrinsics":[[255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,64,95,171,91,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],"header":{"digest":{"logs":[]},"extrinsicsRoot":"0x233cf65d6f67f628b694c7da2d08020a937bc272560df7dd5cc1f11a7f85dc69","number":1565249,"parentHash":"0x0b0f28f64fdef451b6e2636ef18e9670183e1e4841db5a32ce476186611f6baf","stateRoot":"0xc372e08fa6edddd0ee415742eb551b8475100a40fe47a3d6470ad46b9b7b460d"}},"justification":{"hash":"0x737f58ac7f964353c56160187821ef4d2295d196c8479c21c7ae37f708550b57","round_number":1,"signatures":[["0x65d2273adeb04478658e183dc5edf41f1d86e42255442af62e72dbf1e6c0b977","0x6bfe453137983a7ef474cf3108e7cc0260621fac893e92c41d17952430164a1ee1600fd3f8c9d2d8440d391ac1f1a488ac6fd0185fa0ba722698903753c8bb0c"],["0x8c25a8812190a86c0c086b1c4087e31d82e3375652f9a75e828a4301c98245be","0x9e0ecfe993846758fb15920a7103a5cb4199e03481eec1ebf7abb43cb35e9703baf04b606000c788244ccde5d6fb0b22fc940099ced61e8a404d71787757980b"],["0xbb8943a83c953cc96f927ca2e7062e4819f0b258107e495fb40a78d27c2e1ad7","0xa282bc57b27feccc752f194dfe6e2281986a46bac31d06b629c9b62401804ad00a400a67d3770b7470d207d349f167eda72436d6eae7b90469a61eefe1c99800"],["0xea1a15140e562d9f582b38d64d8d1f575b9f837556fdec40fcc3e564259471c7","0x45926cb65bb59595f447eaac5e782029f7fabd47579fe4fec7b79c1c554abf1c31067a500362c2d84aadca3686bfc455d780d2c3265674154d33ea0349db2307"],["0x432d983331d08c86121cd2c86456cf3eeeb5a2f37bab7f2969453b51b4eed783","0x3a09b440194aa714606a2a223422b7795f7d1ac75dca4b6bc5f5031d51b4e282b264d231ca73ee234a814ea5f60e135e7df6dfa02b363ca1204dfe56c2a4ad03"],["0x2e5baf22ac662c0a3883ccf3e17580e6c41f056642040ddc16a877176becdc53","0x02a5605a3f28f7ed9063a4f465601af8625a7fbb69b4757b9838a90ed3e5e1598671853ee106512a833ab1eb7db48f7915b7b48d0b5c2915898d05f54ce23205"],["0x10b9ddcb0d59f795ab64608bd22215b55868ee01efe6d690b8988c63859a6b27","0x04a3e8d9b12163b8c3488968d447bf8b4968bbce55c09ee18ba57f5b9e10dd8f3ae344551d9014e8a1efb0e7e6e83d7cedf440a1d512266a83d4d25d8759ee06"],["0x044b0abaa1854772c75282aa9187935a56926e9c5f5e0b30cf6993c530c09d26","0x3844d377dc958c96eefbb56c777439142af43aebb764c230b74c3f56a4df3207abf4a347d8fe88e5d2641e82c48522079000c02fd89748705d9efb843128e40d"],["0x1689d1d5c9c5b072034ed95aa1ee22c2dd60df78d82de93dc0e3872bfa4c715a","0x481613e2c0b16ae14adc2e463bda352ebb5a839836c4e384bb4770608cdb38ad02b5ca571d19853f6e706ebf880edf12dc5d448d8d331ea2b8926b03aa9bcd0c"],["0x22fdc8c92de49cd1a11f03f591e507b0827e1e19df35b3b0a2a90ee35df4b06c","0xac7802d1e824c656b3e094cf18d1ff4758d2d8df0874a0be123893a0d8c95ddbe9cf40a765b6cfeecb7756b9f18294f9dca35451499c8a7a99d7621d9cd5610b"],["0xcb7cc7b2f624c92c6fad8ee77458a35c7acaade2b03e5f0634509cef1db7ce09","0x5fc45de00c1291ea605c6929ebe77bd5d2d998c7ad44d1f88bce4b86ecefbd447adbbf0290ea12b2b8a34db2c71f266ddccb54f2074340825edd8f7b0b235503"],["0x5d87486121bcfdfbb7b6d8cbd91558059f798587e194c36efb8b379bb8b3dd8e","0x47f046ecb4aca2ba36994b7e11565306a382615f589d26e827de357623c22d271e0998c4617fa8be3902acdf33cb72538839ca731d4476a0f2b41a4c8297000d"],["0xd164f617a7b5144504166c305f9940fb17cd1656e46ba55f344ee4e5f716c12f","0x663502ec1e40325992d2b7307764f6bd524d30968acf2bd3b0a6d43c5f973eebd192a796a455127d6750f407d14650201b225dc107361c2d634e46c3e0c9340e"],["0x3005b5aab73dc485beecf1df7732876a61c81c8f13d7a4883f1243ecbb9497dd","0x4fdcbb79bd4f852ede225e9e90e5bc6c8b9c8760ac016c4f081f1dfc93ef055b8bbd545b459dd82ef107b20013fae2da55fc31784d933a29261d55466628cd01"],["0xfbf09129e1ca12face363366917add306357e8f6221e57edbfa4e820784cf712","0xc620ff8b940e9be7eaf0f5c8d034c8fec33d1fafc2ea5921660486eff5087027e44bb1b38641894aadb055b9bdece9e480f6042ad801a07588bf19f4ba87cb0e"]]}},"id":8} diff --git a/packages/api-codec/src/SignedBlock.spec.js b/packages/api-codec/src/SignedBlock.spec.js new file mode 100644 index 0000000000..6ebf3b9135 --- /dev/null +++ b/packages/api-codec/src/SignedBlock.spec.js @@ -0,0 +1,22 @@ +// 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 rpc from './SignedBlock.rpc.json'; +import SignedBlock from './SignedBlock'; + +describe('SignedBlock', () => { + const block = new SignedBlock().fromJSON(rpc.result); + + it('has the correct stateRoot', () => { + expect( + block.block.header.stateRoot.toString() + ).toEqual('0xc372e08fa6edddd0ee415742eb551b8475100a40fe47a3d6470ad46b9b7b460d'); + }); + + it('has the justification', () => { + expect( + block.justification.hash.toHex() + ).toEqual('0x737f58ac7f964353c56160187821ef4d2295d196c8479c21c7ae37f708550b57'); + }); +}); diff --git a/packages/api-codec/src/SignedBlock.ts b/packages/api-codec/src/SignedBlock.ts new file mode 100644 index 0000000000..d7b1b06bfc --- /dev/null +++ b/packages/api-codec/src/SignedBlock.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 Struct from './codec/Struct'; +import { Justification, JustificationValue } from './Bft'; +import Block, { BlockValue } from './Block'; + +type SignedBlockValue = { + block?: BlockValue, + justification?: JustificationValue +}; + +export default class SignedBlock extends Struct { + constructor (value: SignedBlockValue = {}) { + super({ + block: Block, + justification: Justification + }, value); + } + + get block (): Block { + return this.raw.block as Block; + } + + get justification (): Justification { + return this.raw.justification as Justification; + } +} diff --git a/packages/api-codec/src/Type.ts b/packages/api-codec/src/Type.ts index a9f314d70f..c7c627d356 100644 --- a/packages/api-codec/src/Type.ts +++ b/packages/api-codec/src/Type.ts @@ -39,15 +39,16 @@ export default class Type extends Text { private _cleanupTypes (): Type { const mappings: Array = [ // Remove all the trait prefixes - this._untrait(), + this._removeTraits(), // remove boxing, `Box` -> `Proposal` - this._unwrap('Box<'), + this._removeWrap('Box'), // remove generics, `MisbehaviorReport` -> `MisbehaviorReport` - this._ungeneric(), - // convert `RawAddress` -> `Address` - // convert `PropIndex` -> `ProposalIndex` + this._removeGenerics(), // alias Vec -> Bytes - this._unalias('Vec', 'Bytes') + this._alias('Vec', 'Bytes') + // TODO Check these for possibly matching - + // `RawAddress` -> `Address` (implementation looks the same) + // `PropIndex` -> `ProposalIndex` (implementation looks the same, however meant as diff) ]; this.raw = mappings.reduce((result, fn) => { @@ -76,17 +77,15 @@ export default class Type extends Text { throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`); } - private _unalias (src: string, dest: string): Mapper { + private _alias (src: string, dest: string): Mapper { return (value: string): string => { - while (value.indexOf(src) !== -1) { - value = value.replace(src, dest); - } - - return value; + return value.replace( + new RegExp(src, 'g'), dest + ); }; } - private _ungeneric (): Mapper { + private _removeGenerics (): Mapper { return (value: string): string => { for (let index = 0; index < value.length; index++) { if (value[index] === '<') { @@ -104,7 +103,7 @@ export default class Type extends Text { } // remove the type traits - private _untrait (): Mapper { + private _removeTraits (): Mapper { return (value: string): string => { return value // anything `T::` to end up as `` @@ -117,7 +116,9 @@ export default class Type extends Text { } // remove wrapping values, i.e. Box -> Proposal - private _unwrap (check: string): Mapper { + private _removeWrap (_check: string): Mapper { + const check = `${_check}<`; + return (value: string): string => { let index = 0; diff --git a/packages/api-codec/src/U128.ts b/packages/api-codec/src/U128.ts index 3720ff935e..bc08af199c 100644 --- a/packages/api-codec/src/U128.ts +++ b/packages/api-codec/src/U128.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 BN from 'bn.js'; +import { AnyNumber } from './types'; import UInt from './codec/UInt'; export default class U128 extends UInt { - constructor (value?: UInt | BN | string | number) { + constructor (value?: AnyNumber) { super(value, 128); } } diff --git a/packages/api-codec/src/U16.ts b/packages/api-codec/src/U16.ts index a64cbdf287..0dcbd016fa 100644 --- a/packages/api-codec/src/U16.ts +++ b/packages/api-codec/src/U16.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 BN from 'bn.js'; +import { AnyNumber } from './types'; import UInt from './codec/UInt'; export default class U16 extends UInt { - constructor (value?: UInt | BN | string | number) { + constructor (value?: AnyNumber) { super(value, 16); } } diff --git a/packages/api-codec/src/U256.ts b/packages/api-codec/src/U256.ts index 6edcaefac9..fab6d6d346 100644 --- a/packages/api-codec/src/U256.ts +++ b/packages/api-codec/src/U256.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 BN from 'bn.js'; +import { AnyNumber } from './types'; import UInt from './codec/UInt'; export default class U256 extends UInt { - constructor (value?: UInt | BN | string | number) { + constructor (value?: AnyNumber) { super(value, 256); } } diff --git a/packages/api-codec/src/U32.ts b/packages/api-codec/src/U32.ts index 2f1453b1a2..fbc95f3d82 100644 --- a/packages/api-codec/src/U32.ts +++ b/packages/api-codec/src/U32.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 BN from 'bn.js'; +import { AnyNumber } from './types'; import UInt from './codec/UInt'; export default class U32 extends UInt { - constructor (value?: UInt | BN | string | number) { + constructor (value?: AnyNumber) { super(value, 32); } } diff --git a/packages/api-codec/src/U64.ts b/packages/api-codec/src/U64.ts index 56770ca2f6..0fd1062781 100644 --- a/packages/api-codec/src/U64.ts +++ b/packages/api-codec/src/U64.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 BN from 'bn.js'; +import { AnyNumber } from './types'; import UInt from './codec/UInt'; export default class U64 extends UInt { - constructor (value?: UInt | BN | string | number) { + constructor (value?: AnyNumber) { super(value, 64); } } diff --git a/packages/api-codec/src/U8.ts b/packages/api-codec/src/U8.ts index 0860b5e4b6..4455896e12 100644 --- a/packages/api-codec/src/U8.ts +++ b/packages/api-codec/src/U8.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 BN from 'bn.js'; +import { AnyNumber } from './types'; import UInt from './codec/UInt'; export default class U8 extends UInt { - constructor (value?: UInt | BN | string | number) { + constructor (value?: AnyNumber) { super(value, 8); } } diff --git a/packages/api-codec/src/ValidatorPrefs.spec.js b/packages/api-codec/src/ValidatorPrefs.spec.js new file mode 100644 index 0000000000..92b5f16f62 --- /dev/null +++ b/packages/api-codec/src/ValidatorPrefs.spec.js @@ -0,0 +1,23 @@ +// 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 ValidatorPrefs from './ValidatorPrefs'; + +describe('ValidatorPrefs', () => { + it('starts with empty values', () => { + expect( + new ValidatorPrefs().validatorPayment.toNumber() + ).toEqual(0); + }); + + it('exposes the internal values via get', () => { + const prefs = new ValidatorPrefs({ + unstakeThreshold: 3, + validatorPayment: 12345 + }); + + expect(prefs.unstakeThreshold.toNumber()).toEqual(3); + expect(prefs.validatorPayment.toNumber()).toEqual(12345); + }); +}); diff --git a/packages/api-codec/src/ValidatorPrefs.ts b/packages/api-codec/src/ValidatorPrefs.ts new file mode 100644 index 0000000000..249981b059 --- /dev/null +++ b/packages/api-codec/src/ValidatorPrefs.ts @@ -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 { AnyNumber } from './types'; + +import Struct from './codec/Struct'; +import Balance from './Balance'; +import U32 from './U32'; + +type ValidatorPrefsValue = { + unstakeThreshold?: AnyNumber, + validatorPayment?: AnyNumber +}; + +export default class ValidatorPrefs extends Struct { + constructor (value: ValidatorPrefsValue = {}) { + super({ + unstakeThreshold: U32, + validatorPayment: Balance + }, value); + } + + get unstakeThreshold (): U32 { + return this.raw.unstakeThreshold as U32; + } + + get validatorPayment (): Balance { + return this.raw.validatorPayment as Balance; + } +} diff --git a/packages/api-codec/src/codec/Base.spec.js b/packages/api-codec/src/codec/Base.spec.js new file mode 100644 index 0000000000..879bb61748 --- /dev/null +++ b/packages/api-codec/src/codec/Base.spec.js @@ -0,0 +1,19 @@ +// 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 Base from './Base'; + +describe('Base', () => { + it('has the contructor value on raw', () => { + expect(new Base('foo-bar').raw).toEqual('foo-bar'); + }); + + ['byteLength', 'fromJSON', 'fromU8a', 'toJSON', 'toString', 'toU8a'].forEach((method) => { + it(`has abstract (?) impl for ${method}`, () => { + expect( + () => new Base()[method]() + ).toThrow(/unimplemented/); + }); + }); +}); diff --git a/packages/api-codec/src/codec/Base.ts b/packages/api-codec/src/codec/Base.ts index ca20d02805..942594500b 100644 --- a/packages/api-codec/src/codec/Base.ts +++ b/packages/api-codec/src/codec/Base.ts @@ -8,6 +8,9 @@ // // TODO // - This could probably be abstract, as long as we have the functions abstract as well +// - Not convinced about abstratc - there are a number of extensions to this class that +// don't provide some implementations (e.g. Length, good example and should not be +// used-as-is). In those case it just relies in the throw in here. export default class Base { raw: T; diff --git a/packages/api-codec/src/codec/Enum.spec.js b/packages/api-codec/src/codec/Enum.spec.js new file mode 100644 index 0000000000..191f408514 --- /dev/null +++ b/packages/api-codec/src/codec/Enum.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 Enum from './Enum'; + +describe('Struct', () => { + it('provides a clean toString()', () => { + expect( + new Enum(['foo', 'bar']).toString() + ).toEqual('foo'); + }); + + it('provides a clean toString() (enum)', () => { + expect( + new Enum(['foo', 'bar'], new Enum([], 1)).toNumber() + ).toEqual(1); + }); + + it('converts to and from U8a', () => { + expect( + new Enum(['foo', 'bar']).fromU8a(new Uint8Array([1])).toU8a() + ).toEqual(new Uint8Array([1])); + }); + + it('converts from JSON', () => { + expect( + new Enum(['foo', 'bar']).fromJSON(5).toString() + ).toEqual('5'); + }); +}); diff --git a/packages/api-codec/src/codec/Enum.ts b/packages/api-codec/src/codec/Enum.ts index 03ed403502..65e418ac3e 100644 --- a/packages/api-codec/src/codec/Enum.ts +++ b/packages/api-codec/src/codec/Enum.ts @@ -14,8 +14,12 @@ import Base from './Base'; export default class Enum extends Base { private _strings: Array; - constructor (strings: Array, value: number = 0) { - super(value); + constructor (strings: Array, value: Enum | number = 0) { + super( + value instanceof Enum + ? value.raw + : value + ); this._strings = strings; } @@ -49,6 +53,6 @@ export default class Enum extends Base { } toString (): string { - return this._strings[this.raw]; + return this._strings[this.raw] || `${this.raw}`; } } diff --git a/packages/api-codec/src/codec/EnumType.spec.js b/packages/api-codec/src/codec/EnumType.spec.js new file mode 100644 index 0000000000..636c39a035 --- /dev/null +++ b/packages/api-codec/src/codec/EnumType.spec.js @@ -0,0 +1,33 @@ +// 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 EnumType from './EnumType'; +import Text from '../Text'; +import U32 from '../U32'; + +describe('Struct', () => { + it('provides a clean toString() (raw)', () => { + expect( + new EnumType( + [Text, U32], ['Stringy', 'Inty'] + ).fromU8a(new Uint8Array([0, 2 << 2, 49, 50])).raw.toString() + ).toEqual('12'); + }); + + it('provides a clean toString() (enum)', () => { + expect( + new EnumType( + [Text, U32] + ).fromU8a(new Uint8Array([1, 2 << 2, 49, 50])).toString() + ).toEqual('U32'); + }); + + it('allows checking against defined indexes', () => { + expect( + new EnumType( + [Text, U32], [], [1, 5] + ).fromU8a(new Uint8Array([1, 2 << 2, 49, 50])).toString() + ).toEqual('Text'); + }); +}); diff --git a/packages/api-codec/src/codec/EnumType.ts b/packages/api-codec/src/codec/EnumType.ts index 9b5d49c530..d216b710e9 100644 --- a/packages/api-codec/src/codec/EnumType.ts +++ b/packages/api-codec/src/codec/EnumType.ts @@ -12,41 +12,49 @@ import Base from './Base'; // - It should rather probably extend Enum instead of copying code // - There doesn't actually seem to be a way to get to the actual determined/wrapped value export default class EnumType extends Base> { - private _Type: Array<{ new(value?: any): Base }>; + private _Types: Array<{ new(value?: any): Base }>; private _index: number; + private _indexes: Array; private _strings: Array; - constructor (Type: Array<{ new(value?: any): Base }>, strings: Array, index: number = 0) { + constructor (Types: Array<{ new(value?: any): Base }>, strings: Array = [], indexes: Array = []) { super( - new Type[index]() + new Types[0]() ); - this._Type = Type; - this._index = index; - this._strings = strings; + this._Types = Types; + this._indexes = Types.map((Type, index) => + indexes[index] || index + ); + this._index = this._indexes[0]; + this._strings = Types.map((Type, index) => + strings[index] || Type.name + ); + } + + get Type (): string { + return this._Types[this._index].name; } byteLength (): number { return 1 + this.raw.byteLength(); } - fromJSON (input: any): EnumType { - throw new Error('EnumType:fromJSON: unimplemented'); - } - fromU8a (input: Uint8Array): EnumType { - this._index = input[0]; - this.raw = new this._Type[this._index]().fromU8a(input.subarray(1)); + this._index = this._indexes.indexOf(input[0]); + this.raw = new this._Types[this._index]().fromU8a(input.subarray(1)); return this; } - toJSON (): any { - return this.raw; + setValue (index?: number, value?: any): void { + // NOTE If this is called from constructors, we may have empty values... + this._index = this._indexes.indexOf(index || 0) || 0; + this.raw = new this._Types[this._index](value); } - toU8a (): Uint8Array { - throw new Error('EnumType:toU8a: unimplemented'); + toJSON (): any { + return this.raw; } toNumber (): number { diff --git a/packages/api-codec/src/codec/Length.spec.js b/packages/api-codec/src/codec/Length.spec.js index 6dc0e134f7..8ef0237cc5 100644 --- a/packages/api-codec/src/codec/Length.spec.js +++ b/packages/api-codec/src/codec/Length.spec.js @@ -3,6 +3,7 @@ // of the ISC license. See the LICENSE file for details. import Length from './Length'; +import UInt from './UInt'; describe('Length', () => { it('encodes short u8', () => { @@ -15,7 +16,7 @@ describe('Length', () => { it('encodes max u8 values', () => { expect( - new Length(63).toU8a() + new Length(new UInt(63)).toU8a() ).toEqual( new Uint8Array([0b11111100]) ); diff --git a/packages/api-codec/src/codec/Length.ts b/packages/api-codec/src/codec/Length.ts index 5fad109c3d..cccb11aaba 100644 --- a/packages/api-codec/src/codec/Length.ts +++ b/packages/api-codec/src/codec/Length.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyNumber } from '../types'; + import BN from 'bn.js'; import bnToBn from '@polkadot/util/bn/toBn'; import bnToU8a from '@polkadot/util/bn/toU8a'; @@ -10,6 +12,7 @@ import u8aToBn from '@polkadot/util/u8a/toBn'; import u8aToHex from '@polkadot/util/u8a/toHex'; import Base from './Base'; +import UInt from './UInt'; 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); @@ -30,12 +33,16 @@ const MAX_U32 = new BN(2).pow(new BN(32 - 2)).subn(1); // 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. +// +// FIXME Not crazy about the use of Length. If we look at Vector, Bytes & String, +// the implementations are basically the same. Vector is slightly different since +// it iterates over the length. We need a cleaner way where we have less copied +// code and a more generic implementation around the use of Length. Looking at +// Array or Struct, the same type of wrapper would be useful here. export default class Length extends Base { - constructor (value: Length | BN | number = new BN(0)) { + constructor (value: AnyNumber = new BN(0)) { super( - value instanceof Length - ? value.raw - : bnToBn(value) + UInt.decode(value) ); } @@ -74,26 +81,12 @@ export default class Length extends Base { return this.toU8a().length; } - fromJSON (): Length { - throw new Error('Length::fromJSON: unimplemented'); - } - - fromNumber (value: BN | number): Length { - this.raw = bnToBn(value); - - return this; - } - fromU8a (input: Uint8Array): Length { this.raw = Length.decode(input); return this; } - toJSON (): any { - throw new Error('Length::toJSON: unimplemented'); - } - toHex (): string { return u8aToHex(this.toU8a()); } @@ -102,10 +95,6 @@ export default class Length extends Base { return this.raw.toNumber(); } - toString (): string { - throw new Error('Length::toString: unimplemented'); - } - toU8a (): Uint8Array { return Length.encode(this.raw); } diff --git a/packages/api-codec/src/codec/Option.spec.js b/packages/api-codec/src/codec/Option.spec.js new file mode 100644 index 0000000000..0ad4027461 --- /dev/null +++ b/packages/api-codec/src/codec/Option.spec.js @@ -0,0 +1,46 @@ +// 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 Option from './Option'; +import Text from '../Text'; + +describe('Option', () => { + it('converts fromJSON() with', () => { + const o = new Option(Text).fromJSON('1234'); + + expect(o.isEmpty).toEqual(false); + expect(o.toString()).toEqual('1234'); + }); + + it('converts fromJSON() without', () => { + const o = new Option(Text, '1234').fromJSON(); + + expect(o.isEmpty).toEqual(true); + expect(o.toString()).toEqual(''); + }); + + it('has empty toString() (undefined)', () => { + expect( + new Option(Text).toString() + ).toEqual(''); + }); + + it('has value toString() (provided)', () => { + expect( + new Option(Text).fromU8a(new Uint8Array([1, 4 << 2, 49, 50, 51, 52])).toString() + ).toEqual('1234'); + }); + + it('converts toU8a() with', () => { + expect( + new Option(Text, '1234').toU8a() + ).toEqual(new Uint8Array([1, 4 << 2, 49, 50, 51, 52])); + }); + + it('converts toU8a() without', () => { + expect( + new Option(Text).toU8a() + ).toEqual(new Uint8Array([0])); + }); +}); diff --git a/packages/api-codec/src/codec/Option.ts b/packages/api-codec/src/codec/Option.ts index 59b0255d05..c5f2d5b263 100644 --- a/packages/api-codec/src/codec/Option.ts +++ b/packages/api-codec/src/codec/Option.ts @@ -11,14 +11,14 @@ import Base from './Base'; // implements that - decodes, checks for optionality and wraps the required structure // with a value if/as required/found. export default class Option extends Base> { - private _hasValue: boolean; + private _isEmpty: boolean; constructor (Value: { new(value?: any): Base }, value?: any) { super( new Value(value) ); - this._hasValue = !isUndefined(value); + this._isEmpty = isUndefined(value); } static with (Type: { new(value?: any): Base }): { new(value?: any): Option } { @@ -29,24 +29,28 @@ export default class Option extends Base> { }; } + get isEmpty (): boolean { + return this._isEmpty; + } + get value (): T | undefined { - return this._hasValue - ? this.raw.raw - : undefined; + return this._isEmpty + ? undefined + : this.raw.raw; } byteLength (): number { - const childLength = this._hasValue - ? this.raw.byteLength() - : 0; + const childLength = this._isEmpty + ? 0 + : this.raw.byteLength(); return 1 + childLength; } fromJSON (input: any): Option { - this._hasValue = !isUndefined(input); + this._isEmpty = isUndefined(input); - if (this._hasValue) { + if (!this._isEmpty) { this.raw.fromJSON(input); } @@ -54,9 +58,9 @@ export default class Option extends Base> { } fromU8a (input: Uint8Array): Option { - this._hasValue = input[0] === 1; + this._isEmpty = input[0] === 0; - if (this._hasValue) { + if (!this._isEmpty) { this.raw.fromU8a(input.subarray(1)); } @@ -64,15 +68,15 @@ export default class Option extends Base> { } toJSON (): any { - return this._hasValue - ? this.raw.toJSON() - : undefined; + return this._isEmpty + ? undefined + : this.raw.toJSON(); } toU8a (): Uint8Array { const u8a = new Uint8Array(this.byteLength()); - if (this._hasValue) { + if (!this._isEmpty) { u8a.set([1]); u8a.set(this.raw.toU8a(), 1); } @@ -81,8 +85,8 @@ export default class Option extends Base> { } toString (): string { - return this._hasValue - ? this.raw.toString() - : ''; + return this._isEmpty + ? '' + : this.raw.toString(); } } diff --git a/packages/api-codec/src/codec/Struct.spec.js b/packages/api-codec/src/codec/Struct.spec.js new file mode 100644 index 0000000000..9f7f1de261 --- /dev/null +++ b/packages/api-codec/src/codec/Struct.spec.js @@ -0,0 +1,34 @@ +// 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 Struct from './Struct'; +import Text from '../Text'; +import U32 from '../U32'; + +describe('Struct', () => { + it('provides a clean toString()', () => { + expect( + new ( + Struct.with({ + txt: Text, + u32: U32 + }) + )({ txt: 'foo', u32: 0x123456 }).toString() + ).toEqual(`{txt: foo, u32: 0x00123456}`); + }); + + it('exposes the types', () => { + expect( + new Struct({ + foo: Text, + bar: Text, + baz: U32 + }).Type + ).toEqual({ + foo: 'Text', + bar: 'Text', + baz: 'U32' + }); + }); +}); diff --git a/packages/api-codec/src/codec/Struct.ts b/packages/api-codec/src/codec/Struct.ts index 95063cc24a..8e431c89b4 100644 --- a/packages/api-codec/src/codec/Struct.ts +++ b/packages/api-codec/src/codec/Struct.ts @@ -6,59 +6,87 @@ import u8aConcat from '@polkadot/util/u8a/concat'; import Base from './Base'; -// A Struct defines an Object with key/values - where the values are CodecBase values. It removes +// A Struct defines an Object with key/values - where the values are Base values. It removes // a lot of repetition from the actual coding, define a structure type, pass it the key/Base // values in the constructor and it manages the decoding. It is important that the constructor // values matches 100% to the order in th Rust code, i.e. don't go crazy and make it alphabetical, // it needs to decoded in the specific defined order. -// -// TODO: -// - Check the constructor, something is really, really wrong with the way the defs are used export default class Struct < + // The actual Class structure, i.e. key -> Class S = { [index: string]: { new(value?: any): Base } }, + // internal type, instance of classes mapped by key T = { [K in keyof S]: Base }, - V = { [K in keyof S]: any } + // input values, mapped by key can be anything (construction) + V = { [K in keyof S]: any }, + // type names, mapped by key, name of Class in S + E = { [K in keyof S]: string } > extends Base { - constructor (Def: S, value: V = {} as V) { - super( - Object.keys(Def).reduce((raw: T, key) => { - // @ts-ignore Ok, something weid is going on here or I just don't get it... it works, - // so ignore the checker, although it drives me batty. (It started when the [key in keyof T] - // was added, the idea is to provide better checks, which does backfire here, but works - // externally.) - raw[key] = new Def[key](value[key]); + private _Types: E; - return raw; - }, {} as T) + constructor (Types: S, value: V = {} as V) { + super( + Object + .keys(Types) + .reduce((raw: T, key) => { + // @ts-ignore FIXME Ok, something weird is going on here or I just don't get it... + // it works, so ignore the checker, although it drives me batty. (It started when + // the [key in keyof T] was added, the idea is to provide better checks, which + // does backfire here, but works externally.) + raw[key] = new Types[key](value[key]); + + return raw; + }, {} as T) ); + + this._Types = Object + .keys(Types) + .reduce((result: E, key) => { + // @ts-ignore Same as above, can't do a simple one, I'm missing something simple + result[key] = Types[key].name; + + return result; + }, {} as E); } static with < S = { [index: string]: { new(value?: any): Base } } - > (Def: S): { new(value?: any): Struct } { + > (Types: S): { new(value?: any): Struct } { return class extends Struct { constructor (value?: any) { - super(Def, value); + super(Types, value); } }; } + get Type (): E { + return this._Types; + } + byteLength (): number { return Object.values(this.raw).reduce((length, entry) => { return length += entry.byteLength(); }, 0); } - fromJSON (input: any): Struct { - Object.keys(this.raw).forEach((key) => { + fromJSON (input: any): Struct { + // NOTE From Rust, anonymous structures are encoded to Arrays, here + // we handle that case, taking each value in the array and passing it + // (in order) to the actual decoders (See e.g. SignedBlock.spec.json) + const isArrayIn = Array.isArray(input); + + Object.keys(this.raw).forEach((key, index) => { // @ts-ignore as above... - this.raw[key].fromJSON(input[key]); + this.raw[key].fromJSON( + isArrayIn + ? input[index] + : input[key] + ); }); return this; } - fromU8a (input: Uint8Array): Struct { + fromU8a (input: Uint8Array): Struct { Object.keys(this.raw).reduce((offset, key) => { // @ts-ignore as above... this.raw[key].fromU8a(input.subarray(offset)); diff --git a/packages/api-codec/src/codec/U8a.ts b/packages/api-codec/src/codec/U8a.ts index b44ea6530d..c82aac06bb 100644 --- a/packages/api-codec/src/codec/U8a.ts +++ b/packages/api-codec/src/codec/U8a.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from '../types'; + import u8aToHex from '@polkadot/util/u8a/toHex'; import toU8a from '@polkadot/util/u8a/toU8a'; @@ -12,7 +14,7 @@ import Base from './Base'; // 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 U8a extends Base { - constructor (value: U8a | string | Uint8Array | Array = new Uint8Array()) { + constructor (value: AnyU8a = new Uint8Array()) { super( value instanceof U8a ? value.raw diff --git a/packages/api-codec/src/codec/U8aFixed.ts b/packages/api-codec/src/codec/U8aFixed.ts index 78a83b8859..e5becec2f0 100644 --- a/packages/api-codec/src/codec/U8aFixed.ts +++ b/packages/api-codec/src/codec/U8aFixed.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from '../types'; + import U8a from './U8a'; type BitLength = 256 | 512; @@ -11,7 +13,7 @@ type BitLength = 256 | 512; export default class U8aFixed extends U8a { protected _bitLength: number; - constructor (value: U8a | string | Uint8Array = new Uint8Array(), bitLength: BitLength = 256) { + constructor (value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) { super(value); this._bitLength = bitLength; diff --git a/packages/api-codec/src/codec/UInt.spec.js b/packages/api-codec/src/codec/UInt.spec.js new file mode 100644 index 0000000000..d3bac12d00 --- /dev/null +++ b/packages/api-codec/src/codec/UInt.spec.js @@ -0,0 +1,46 @@ +// 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 UInt from './UInt'; + +describe('UInt', () => { + it('provides a toBn interface', () => { + expect( + new UInt(987).toBn().toNumber() + ).toEqual(987); + }); + + it('provides a toNumber interface', () => { + expect( + new UInt(4567).toNumber() + ).toEqual(4567); + }); + + it('converts to LE from the provided value', () => { + expect( + new UInt(1234567).toU8a() + ).toEqual(new Uint8Array([135, 214, 18, 0, 0, 0, 0, 0])); + }); + + it('converts to LE from the provided value (bitLength)', () => { + expect( + new UInt(1234567, 32).toU8a() + ).toEqual(new Uint8Array([135, 214, 18, 0])); + }); + + it('converts to hex/string', () => { + const u = new UInt('0x12', 16); + + expect(u.toHex()).toEqual('0x0012'); + expect(u.toString()).toEqual('0x0012'); + }); + + it('converts to equivalents', () => { + const a = new UInt('123'); + + expect( + new UInt(a).toNumber() + ).toEqual(123); + }); +}); diff --git a/packages/api-codec/src/codec/UInt.ts b/packages/api-codec/src/codec/UInt.ts index 06de236be2..5bf009405f 100644 --- a/packages/api-codec/src/codec/UInt.ts +++ b/packages/api-codec/src/codec/UInt.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyNumber } from '../types'; + import BN from 'bn.js'; import isHex from '@polkadot/util/is/hex'; import isString from '@polkadot/util/is/string'; @@ -24,7 +26,7 @@ type BitLength = 8 | 16 | 32 | 64 | 128 | 256; export default class UInt extends Base { private _bitLength: BitLength; - constructor (value: UInt | BN | string | number = 0, bitLength: BitLength = 64) { + constructor (value: AnyNumber = 0, bitLength: BitLength = 64) { super( UInt.decode(value) ); @@ -32,7 +34,7 @@ export default class UInt extends Base { this._bitLength = bitLength; } - static decode (value: UInt | BN | string | number): BN { + static decode (value: AnyNumber): BN { if (value instanceof UInt) { return value.raw; } else if (isHex(value)) { @@ -60,6 +62,10 @@ export default class UInt extends Base { return this; } + toHex (): string { + return bnToHex(this.raw, this._bitLength); + } + toJSON (): any { return this.toString(); } @@ -69,7 +75,7 @@ export default class UInt extends Base { } toString (): string { - return bnToHex(this.raw, this._bitLength); + return this.toHex(); } toBn (): BN { diff --git a/packages/api-codec/src/codec/Vector.spec.js b/packages/api-codec/src/codec/Vector.spec.js index b436716539..0f46885535 100644 --- a/packages/api-codec/src/codec/Vector.spec.js +++ b/packages/api-codec/src/codec/Vector.spec.js @@ -37,6 +37,10 @@ describe('Vector', () => { ).toEqual('[6, 7]'); }); + it('exposes the type', () => { + expect(array.Type).toEqual('Text'); + }); + describe('array-like functions', () => { it('allows retrieval of a specific item', () => { expect( diff --git a/packages/api-codec/src/codec/Vector.ts b/packages/api-codec/src/codec/Vector.ts index d977beb3c8..c3339a31b2 100644 --- a/packages/api-codec/src/codec/Vector.ts +++ b/packages/api-codec/src/codec/Vector.ts @@ -39,16 +39,20 @@ export default class Vector < }; } - byteLength (): number { - return this.raw.reduce((total, raw) => { - return total + raw.byteLength(); - }, this._length.byteLength()); + get Type (): string { + return this._Type.name; } get length (): number { return this.raw.length; } + byteLength (): number { + return this.raw.reduce((total, raw) => { + return total + raw.byteLength(); + }, this._length.byteLength()); + } + at (index: number): T { return this.raw[index]; } diff --git a/packages/api-codec/src/codec/index.ts b/packages/api-codec/src/codec/index.ts new file mode 100644 index 0000000000..e7d9aedd82 --- /dev/null +++ b/packages/api-codec/src/codec/index.ts @@ -0,0 +1,12 @@ +// 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. + +// NOTE We are not exporting everything here. These _should_ be enough to use the +// actual interfaces from a "create-a-working-coder" perspective. If not, we should +// expand with slight care (for instance, Length is really only used internally to +// others, so there _should_ not be need for direct use) + +export { default as Base } from './Base'; +export { default as Struct } from './Struct'; +export { default as Vector } from './Vector'; diff --git a/packages/api-codec/src/index.ts b/packages/api-codec/src/index.ts new file mode 100644 index 0000000000..ae32ed0d54 --- /dev/null +++ b/packages/api-codec/src/index.ts @@ -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. + +// NOTE We are not re-exporting the index.ts from codec here. The reasoning being +// that these should be enough to actually _use_ the codec, i.e. from a api-user +// perspective these are the value classes. (Codec is for the cases where you need +// to construct values dynamically) + +export { default as AccountId } from './AccountId'; +export { default as AccountIndex } from './AccountIndex'; +export { default as Address } from './Address'; +export { default as AuthorityId } from './AuthorityId'; +export { default as Balance } from './Balance'; +// NOTE Bft items are only used in internal structures +// export * from './Bft; +export { default as Block } from './Block'; +export { default as BlockNumber } from './BlockNumber'; +export { default as Bool } from './Bool'; +export { default as Bytes } from './Bytes'; +export { default as Extrinsic } from './Extrinsic'; +// NOTE These are currently only used internally, no direct mapping to Rust strings +// export { default as H256 } from './H256'; +// export { default as H512 } from './H512'; +export { default as Hash } from './Hash'; +export { default as Header } from './Header'; +export { default as KeyValue } from './KeyValue'; +export { default as Metadata } from './Metadata'; +export { default as MisbehaviorReport } from './MisbehaviorReport'; +// NOTE Nonce is renamed to Index +export { default as Index } from './Nonce'; +export { default as PropIndex } from './PropIndex'; +export { default as ProposalIndex } from './ProposalIndex'; +export { default as RawAddress } from './RawAddress'; +export { default as ReferendumIndex } from './ReferendumIndex'; +export { default as Signature } from './Signature'; +export { default as SignedBlock } from './SignedBlock'; +// NOTE Text is currently only used internally, export not needed +// export { default as Text } from './Text'; +// NOTE Type is currently only used internally (possibly in codec-related work) +// export { default as Type } from './Type'; +export { default as U8 } from './U8'; +export { default as U16 } from './U16'; +export { default as U32 } from './U32'; +export { default as U64 } from './U64'; +export { default as U128 } from './U128'; +export { default as U256 } from './U256'; +export { default as ValidatorPrefx } from './ValidatorPrefs'; +export { default as UoteIndex } from './VoteIndex'; diff --git a/packages/api-codec/src/types.d.ts b/packages/api-codec/src/types.d.ts new file mode 100644 index 0000000000..437d99afd8 --- /dev/null +++ b/packages/api-codec/src/types.d.ts @@ -0,0 +1,12 @@ +// 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 U8a from './codec/U8a'; +import UInt from './codec/UInt'; + +export type AnyNumber = UInt | BN | number | string; + +export type AnyU8a = U8a | Uint8Array | Array | string;