-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
web3js.ts
79 lines (71 loc) 路 1.9 KB
/
web3js.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
69
70
71
72
73
74
75
76
77
78
79
import { Message, PublicKey, Signer, Transaction } from '@solana/web3.js'
import nacl from 'tweetnacl'
import { Buffer } from 'buffer'
import { forceUint8Array } from './utils'
export const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => {
if (Buffer.isBuffer(arr)) {
return arr
} else if (arr instanceof Uint8Array) {
return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength)
} else {
return Buffer.from(arr)
}
}
type PartialSign = (
this: Transaction,
message: Message,
...signers: Array<Signer>
) => void
type AddSignature = (
this: Transaction,
pubkey: PublicKey,
signature: Buffer
) => void
type VerifySignatures = (
this: Transaction,
signData: Buffer,
requireAllSignatures: boolean
) => boolean
export type TransactionWithInternals = Transaction & {
_partialSign: PartialSign
_addSignature: AddSignature
_verifySignatures: VerifySignatures
}
export function partialSign(
this: TransactionWithInternals,
message: Message,
...signers: Array<Signer>
) {
const serializedMessage = message.serialize()
const signData = forceUint8Array(serializedMessage)
signers.forEach((signer) => {
const secretKey = forceUint8Array(signer.secretKey)
const signature = nacl.sign.detached(signData, secretKey)
this._addSignature(signer.publicKey, toBuffer(signature))
})
}
export function verifySignatures(
this: TransactionWithInternals,
signData: Buffer,
requireAllSignatures: boolean
): boolean {
for (const { signature, publicKey } of this.signatures) {
if (signature === null) {
if (requireAllSignatures) {
return false
}
} else {
const publicKeyBuf = publicKey.toBuffer()
if (
!nacl.sign.detached.verify(
forceUint8Array(signData),
forceUint8Array(signature),
forceUint8Array(publicKeyBuf)
)
) {
return false
}
}
}
return true
}