-
Notifications
You must be signed in to change notification settings - Fork 47
/
nonce-tx-middleware.ts
68 lines (58 loc) · 2.14 KB
/
nonce-tx-middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import debug from 'debug'
import { Address } from '../address'
import { ITxMiddlewareHandler, Client, ITxResults } from '../client'
import { bytesToHex } from '../crypto-utils'
import { NonceTx } from '../proto/loom_pb'
const log = debug('nonce-tx-middleware')
export const INVALID_TX_NONCE_ERROR = 'Invalid tx nonce'
export function isInvalidTxNonceError(err: any): boolean {
return err instanceof Error && err.message === INVALID_TX_NONCE_ERROR
}
/**
* Wraps data in a NonceTx.
* This middleware obtains the latest nonce from the chain for each tx.
* The Loom DAppChain keeps track of the nonce of the last committed tx to prevent replay attacks.
*/
export class NonceTxMiddleware implements ITxMiddlewareHandler {
private _publicKey: Uint8Array | null = null
private _account: Address | null = null
private _client: Client
constructor(publicKey: Uint8Array, client: Client)
constructor(account: Address, client: Client)
constructor(publicKeyOrAccount: Uint8Array | Address, client: Client) {
if (publicKeyOrAccount instanceof Address) {
this._account = publicKeyOrAccount
} else {
this._publicKey = publicKeyOrAccount
}
this._client = client
}
async Handle(txData: Readonly<Uint8Array>): Promise<Uint8Array> {
const key = this._publicKey ? bytesToHex(this._publicKey) : undefined
const account = this._account ? this._account.toString() : undefined
const nonce = await this._client.getAccountNonceAsync({ key, account })
log(`Next nonce ${nonce + 1}`)
const tx = new NonceTx()
tx.setInner(txData as Uint8Array)
tx.setSequence(nonce + 1)
return tx.serializeBinary()
}
HandleResults(results: ITxResults): ITxResults {
const { validation, commit } = results
if (
validation &&
validation.code === 1 &&
(validation.log && validation.log.indexOf('sequence number does not match') !== -1)
) {
throw new Error(INVALID_TX_NONCE_ERROR)
}
if (
commit &&
commit.code === 1 &&
(commit.log && commit.log.indexOf('sequence number does not match') !== -1)
) {
throw new Error(INVALID_TX_NONCE_ERROR)
}
return results
}
}