Skip to content

Commit

Permalink
refactor(encoder)!: remove required prefix param
Browse files Browse the repository at this point in the history
BREAKING CHANGE: since the prefix is evaluated by the type
itself the required prefix parameter is no more required.

rewrite
```js
decode('cb_DA6sWJo=', 'cb')
```
to
```js
decode('cb_DA6sWJo=')
```
  • Loading branch information
subhod-i committed May 18, 2022
1 parent 307557e commit dec13d7
Show file tree
Hide file tree
Showing 12 changed files with 22 additions and 36 deletions.
1 change: 0 additions & 1 deletion docs/guides/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ BaseError
│ │ InvalidTxError
│ │ InvalidTxParamsError
│ │ NoDefaultAensPointerError
│ │ PrefixMismatchError
│ │ PrefixNotFoundError
│ │ SchemaNotFoundError
│ │ TagNotFoundError
Expand Down
2 changes: 1 addition & 1 deletion src/account/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export abstract class _AccountBase {
): Promise<EncodedData<'tx'>> {
const prefixes = [this.getNetworkId({ networkId })]
if (innerTx === true) prefixes.push('inner_tx')
const rlpBinaryTx = decode(tx, 'tx')
const rlpBinaryTx = decode(tx)
const txWithNetworkId = Buffer.concat([Buffer.from(prefixes.join('-')), hash(rlpBinaryTx)])

const signatures = [await this.sign(txWithNetworkId, options)]
Expand Down
2 changes: 1 addition & 1 deletion src/account/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class _AccountMemory extends _AccountBase {
const secretKey = typeof keypair.secretKey === 'string'
? Buffer.from(keypair.secretKey, 'hex')
: keypair.secretKey
if (!isValidKeypair(secretKey, decode(keypair.publicKey, 'ak'))) {
if (!isValidKeypair(secretKey, decode(keypair.publicKey))) {
throw new InvalidKeypairError('Invalid Key Pair')
}

Expand Down
4 changes: 2 additions & 2 deletions src/account/multiple.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class _AccountMultiple extends _AccountResolver {
_resolveAccount (account: Account | EncodedData<'ak'> = this.selectedAddress): _AccountBase {
if (typeof account === 'string') {
const address = account as EncodedData<'ak'>
decode(address, 'ak')
decode(address)
if (this.accounts[address] == null) throw new UnavailableAccountError(account)
account = this.accounts[address]
}
Expand Down Expand Up @@ -109,7 +109,7 @@ class _AccountMultiple extends _AccountResolver {
* @example selectAccount('ak_xxxxxxxx')
*/
selectAccount (address: EncodedData<'ak'>): void {
decode(address, 'ak')
decode(address)
if (this.accounts[address] == null) throw new UnavailableAccountError(address)
this.selectedAddress = address
}
Expand Down
4 changes: 2 additions & 2 deletions src/utils/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export function getAddressFromPriv (secret: string | Uint8Array): string {
*/
export function isAddressValid (address: string, prefix: EncodingType = 'ak'): boolean {
try {
decode(address as EncodedData<typeof prefix>, prefix)
decode(address as EncodedData<typeof prefix>)
return true
} catch (e) {
return false
Expand Down Expand Up @@ -102,7 +102,7 @@ export function hash (input: Data): Buffer {
* @return {String} - Contract address
*/
export function encodeContractAddress (owner: EncodedData<'ak'>, nonce: number): string {
const publicKey = decode(owner, 'ak')
const publicKey = decode(owner)
const binary = Buffer.concat([publicKey, encodeUnsigned(nonce)])
return encode(hash(binary), 'ct')
}
Expand Down
14 changes: 5 additions & 9 deletions src/utils/encoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import {
DecodeError,
ArgumentError,
InvalidChecksumError,
PayloadLengthError,
PrefixMismatchError
PayloadLengthError
} from './errors'

/**
Expand All @@ -19,8 +18,9 @@ export function sha256hash (input: Uint8Array | string): Buffer {
}

// based on https://github.com/aeternity/protocol/blob/master/node/api/api_encoding.md
const base64Types = ['ba', 'cb', 'or', 'ov', 'pi', 'ss', 'cs', 'ck', 'cv', 'st', 'tx']
const base58Types = ['ak', 'bf', 'bs', 'bx', 'ch', 'cm', 'ct', 'kh', 'mh', 'nm', 'ok', 'oq', 'pp', 'sg', 'th']
const base64Types = ['ba', 'cb', 'or', 'ov', 'pi', 'ss', 'cs', 'ck', 'cv', 'st', 'tx'] as const
const base58Types = ['ak', 'bf', 'bs', 'bx', 'ch', 'cm', 'ct', 'kh', 'mh', 'nm', 'ok', 'oq', 'pp', 'sg', 'th'] as const

export type EncodingType = typeof base64Types[number] | typeof base58Types[number]
export type EncodedData<Type extends EncodingType> = `${Type}_${string}`
// TODO: add all types with a fixed length
Expand Down Expand Up @@ -73,14 +73,10 @@ const parseType = (maybeType: unknown): [EncodingType, typeof base64] => {
* @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
* @param {EncodedData<EncodingType>} data An Base58/64check encoded and prefixed string
* (ex tx_..., sg_..., ak_....)
* @param {string} [requiredPrefix] Ensure that data have this prefix
* @return {Buffer} Decoded data
*/
export function decode (data: EncodedData<EncodingType>, requiredPrefix?: EncodingType): Buffer {
export function decode (data: EncodedData<EncodingType>): Buffer {
const [prefix, encodedPayload, extra] = data.split('_')
if (requiredPrefix != null && requiredPrefix !== prefix) {
throw new PrefixMismatchError(prefix, requiredPrefix)
}
if (encodedPayload == null) throw new DecodeError(`Encoded string missing payload: ${data}`)
if (extra != null) throw new DecodeError(`Encoded string have extra parts: ${data}`)
const [type, { decode }] = parseType(prefix)
Expand Down
7 changes: 0 additions & 7 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,13 +555,6 @@ export class NoDefaultAensPointerError extends TransactionError {
}
}

export class PrefixMismatchError extends TransactionError {
constructor (prefix: string, requiredPrefix: string) {
super(`Encoded string have a wrong type: ${prefix} (expected: ${requiredPrefix})`)
this.name = 'PrefixMismatchError'
}
}

export class PrefixNotFoundError extends TransactionError {
constructor (tag: string) {
super(`Prefix for id-tag ${tag} not found.`)
Expand Down
8 changes: 4 additions & 4 deletions test/integration/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,12 +383,12 @@ describe('Channel', function () {
const initiatorAddr: EncodedData<'ak'> = await aeSdkInitiatior.address()
const responderAddr: EncodedData<'ak'> = await aeSdkResponder.address()
const params = { accounts: [initiatorAddr, responderAddr] }
const initiatorPoi = await initiatorCh.poi(params)
const responderPoi = await responderCh.poi(params)
const initiatorPoi: EncodedData<'pi'> = await initiatorCh.poi(params)
const responderPoi: EncodedData<'pi'> = await responderCh.poi(params)
initiatorPoi.should.be.a('string')
responderPoi.should.be.a('string')
const unpackedInitiatorPoi = unpackTx(decode(initiatorPoi, 'pi'), true)
const unpackedResponderPoi = unpackTx(decode(responderPoi, 'pi'), true)
const unpackedInitiatorPoi = unpackTx(decode(initiatorPoi), true)
const unpackedResponderPoi = unpackTx(decode(responderPoi), true)
buildTx(unpackedInitiatorPoi.tx, unpackedInitiatorPoi.txType, { prefix: 'pi' }).tx.should.equal(initiatorPoi)
buildTx(unpackedResponderPoi.tx, unpackedResponderPoi.txType, { prefix: 'pi' }).tx.should.equal(responderPoi)
})
Expand Down
5 changes: 3 additions & 2 deletions test/unit/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ import { assert, expect } from 'chai'
import * as Crypto from '../../src/utils/crypto'
import { buildTxHash, unpackTx } from '../../src/tx/builder'
import { decode } from '../../src/tx/builder/helpers'
import { EncodedData } from '../../src/utils/encoder'

// These keys are fixations for the encryption lifecycle tests and will
// not be used for signing
const privateKeyAsHex = '4d881dd1917036cc231f9881a0db978c8899dd76a817252418606b02bf6ab9d22378f892b7cc82c2d2739e994ec9953aa36461f1eb5a4a49a5b0de17b3d23ae8'
const privateKey = Buffer.from(privateKeyAsHex, 'hex')
const publicKeyWithPrefix = 'ak_Gd6iMVsoonGuTF8LeswwDDN2NF5wYHAoTRtzwdEcfS32LWoxm'
const publicKey = decode(publicKeyWithPrefix, 'ak')
const publicKeyWithPrefix: EncodedData<'ak'> = 'ak_Gd6iMVsoonGuTF8LeswwDDN2NF5wYHAoTRtzwdEcfS32LWoxm'
const publicKey = decode(publicKeyWithPrefix)

const txBinaryAsArray = [
248, 76, 12, 1, 160, 35, 120, 248, 146, 183, 204, 130, 194, 210, 115, 158, 153, 78, 201, 149, 58,
Expand Down
4 changes: 2 additions & 2 deletions test/unit/hd-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
getSaveHDWalletAccounts,
DerivationError
} from '../../src/utils/hd-wallet'
import { encode, decode } from '../../src/utils/encoder'
import { encode, decode, EncodedData } from '../../src/utils/encoder'

describe('hd wallet', () => {
const testMnemonicSeed = Buffer.from('Git7bFJkmfC1Ho+6YFSFuxSzmDZydmjzk8FubrPDz4PmrkORlBDlfnPTk02Wq9Pj2ZdQ5cTA0SxHKGrq3xSjOw==', 'base64')
Expand Down Expand Up @@ -174,7 +174,7 @@ describe('hd wallet', () => {

it('get HdWalletAccount from seed', () => {
const wallet = getHdWalletAccountFromSeed(testMnemonicSeed, 0)
decode(wallet.publicKey, 'ak')
decode(wallet.publicKey as EncodedData<'ak'>)
})

it('Derive child with invalid path', () => {
Expand Down
4 changes: 2 additions & 2 deletions test/unit/memory-account.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { describe, it } from 'mocha'
import { expect } from 'chai'
import MemoryAccount from '../../src/account/memory'
import { generateKeyPair } from '../../src/utils/crypto'
import { InvalidKeypairError, PrefixMismatchError } from '../../src/utils/errors'
import { InvalidKeypairError, DecodeError } from '../../src/utils/errors'

const testAcc = generateKeyPair()

Expand All @@ -33,7 +33,7 @@ describe('MemoryAccount', function () {

it('Fail on invalid publicKey', async () => {
expect(() => MemoryAccount({ keypair: { publicKey: ' ', secretKey: testAcc.secretKey } }))
.to.throw(PrefixMismatchError, 'Encoded string have a wrong type: (expected: ak)')
.to.throw(DecodeError, 'Encoded string missing payload')
})

it('Fail on invalid publicKey', async () => {
Expand Down
3 changes: 0 additions & 3 deletions test/unit/tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,6 @@ describe('Tx', function () {
it('throws if invalid checksum', () => expect(() => decode('ak_23aaaaa'))
.to.throw('Invalid checksum'))

it('throws if not matching type', () => expect(() => decode('cb_DA6sWJo=', 'ak'))
.to.throw('Encoded string have a wrong type: cb (expected: ak)'))

it('throws if invalid size', () => expect(() => decode('ak_An6Ui6sE1F'))
.to.throw('Payload should be 32 bytes, got 4 instead'))
})
Expand Down

0 comments on commit dec13d7

Please sign in to comment.