-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
241 lines (213 loc) · 8.8 KB
/
Copy pathindex.js
File metadata and controls
241 lines (213 loc) · 8.8 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { KMSClient, CreateKeyCommand, GetPublicKeyCommand, SignCommand } from '@aws-sdk/client-kms'
import { keccak256 } from 'ethereumjs-util'
import { Transaction } from 'ethereumjs-tx'
import { createAlchemyWeb3 } from '@alch/alchemy-web3'
import log from 'ololog'
import ethutil from 'ethereumjs-util'
import asn1 from 'asn1.js'
import { BN } from 'bn.js'
const client = new KMSClient({
accessKeyId: process.env.AWS_ACCESS_KEY_ID, // credentials for your IAM user
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, // credentials for your IAM user
region: 'us-east-1'
})
const EcdsaSigAsnParse = asn1.define('EcdsaSig', async function () {
// parsing this according to https://tools.ietf.org/html/rfc3279#section-2.2.3
this.seq().obj(
this.key('r').int(),
this.key('s').int()
)
})
const EcdsaPubKey = asn1.define('EcdsaPubKey', async function () {
// parsing this according to https://tools.ietf.org/html/rfc5480#section-2
this.seq().obj(
this.key('algo')
.seq()
.obj(this.key('a').objid(), this.key('b').objid()),
this.key('pubKey').bitstr()
)
})
export async function createKey() {
const createKeyCommand = new CreateKeyCommand({
CustomerMasterKeySpec: 'ECC_SECG_P256K1',
KeyUsage: 'SIGN_VERIFY'
})
const response = await client.send(createKeyCommand)
return response.KeyMetadata.KeyId
}
export async function sign(msgHash, keyId) {
const client = new KMSClient({
accessKeyId: process.env.AWS_ACCESS_KEY_ID, // credentials for your IAM user
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, // credentials for your IAM user
region: 'us-east-1'
})
const params = {
KeyId: keyId,
Message: msgHash,
SigningAlgorithm: 'ECDSA_SHA_256',
MessageType: 'DIGEST'
}
const command = new SignCommand(params)
const response = await client.send(command)
return response
}
export async function getPublicKey(keyID) {
const getPublicKeyCommand = new GetPublicKeyCommand({
KeyId: keyID
})
const response = await client.send(getPublicKeyCommand)
return response.PublicKey
}
export async function getEthereumAddress(publicKey) {
const url = process.env.ALCHEMY_URL
const web3 = createAlchemyWeb3(url)
const res = await EcdsaPubKey.decode(Buffer.from(publicKey), 'der')
let pubKeyBuffer = Buffer.from(res.pubKey.data)
pubKeyBuffer = pubKeyBuffer.slice(1, pubKeyBuffer.length)
const address = keccak256(pubKeyBuffer) // keccak256 hash of publicKey
const buf2 = Buffer.from(address, 'hex')
const ethAddr = '0x' + buf2.slice(-20).toString('hex') // take last 20 bytes as ethereum adress
const checksum = web3.utils.toChecksumAddress(ethAddr)
return checksum
}
export async function findEthereumSignature(plaintext, keyId) {
const signature = await sign(plaintext, keyId)
if (signature.Signature === undefined) {
throw new Error('Signature is undefined.')
}
const decoded = await EcdsaSigAsnParse.decode(Buffer.from(signature.Signature), 'der')
const r = new BN(decoded.r)
let s = new BN(decoded.s)
const secp256k1N = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16) // max value on the curve
const secp256k1halfN = secp256k1N.div(new BN(2)) // half of the curve
// Because of EIP-2 not all elliptic curve signatures are accepted
// the value of s needs to be SMALLER than half of the curve
// i.e. we need to flip s if it's greater than half of the curve
if (s.gt(secp256k1halfN)) {
// According to EIP2 https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
// if s < half the curve we need to invert it
// s = curve.n - s
s = secp256k1N.sub(s)
return { r, s }
}
// if s is less than half of the curve, we're on the "good" side of the curve, we can just return
return { r, s }
}
export async function recoverAddressFromSignature(msg, r, s, v) {
const rBuffer = r.toBuffer()
const sBuffer = s.toBuffer()
const publicKey = ethutil.ecrecover(msg, v, rBuffer, sBuffer)
const addressBuffer = ethutil.pubToAddress(publicKey)
var recoveredEthereumAddress = ethutil.bufferToHex(addressBuffer)
return recoveredEthereumAddress
}
export async function findRightKey(msg, r, s, expectedEthereumAddress) {
let v = 27
let address = await recoverAddressFromSignature(msg, r, s, v)
if (address !== expectedEthereumAddress) {
v = 28
address = await recoverAddressFromSignature(msg, r, s, v)
}
return { address, v }
}
export async function awsKmsEthereumTransactionCreate(rawTransaction, sourceAddress, keyId) {
const url = process.env.ALCHEMY_URL
const web3 = createAlchemyWeb3(url)
const publicKey = await getPublicKey(keyId)
const ethereumAddress = await getEthereumAddress(Buffer.from(publicKey))
if (ethereumAddress !== web3.utils.toChecksumAddress(sourceAddress)) {
return {
success: false,
statusCode: 9664,
reason: 'incorrect_keyId'
}
}
const ethereumAddressHash = ethutil.keccak(Buffer.from(ethereumAddress))
const signature = await findEthereumSignature(ethereumAddressHash, keyId)
const recoveredAddress = await findRightKey(ethereumAddressHash, signature.r, signature.s, ethereumAddress)
const txParams = {
to: rawTransaction.to,
value: rawTransaction.value,
gas: rawTransaction.gas,
gasPrice: rawTransaction.gasPrice,
gasLimit: rawTransaction.gasLimit,
nonce: await web3.eth.getTransactionCount(ethereumAddress),
data: rawTransaction.data,
r: await signature.r.toBuffer(),
s: await signature.s.toBuffer(),
v: recoveredAddress.v
}
const transaction = new Transaction(txParams)
const txHash = transaction.hash(false)
const correctSignature = await findEthereumSignature(txHash, keyId)
transaction.r = await correctSignature.r.toBuffer()
transaction.s = await correctSignature.s.toBuffer()
transaction.v = 27
const senderAddress = '0x' + transaction.getSenderAddress().toString('hex')
const senderCheckSum = web3.utils.toChecksumAddress(senderAddress)
if (senderCheckSum === ethereumAddress) {
return transaction
} else {
transaction.v = 28
const senderAddress2 = '0x' + transaction.getSenderAddress().toString('hex')
const senderCheckSum2 = web3.utils.toChecksumAddress(senderAddress2)
if (senderCheckSum2 === ethereumAddress) {
return transaction
} else {
await awsKmsEthereumTransactionCreate(rawTransaction, sourceAddress, keyId)
}
}
}
export async function sendTransaction(transaction) {
console.log('sendTransaction()')
console.log('transaction: ')
console.log(transaction)
if (process.env.NODE_ENVIRONMENT === 'development') {
log.cyan('Send Transaction ---- START')
}
const url = process.env.ALCHEMY_ENDPOINT + process.env.ALCHEMY_KEY
const web3 = createAlchemyWeb3(url)
try {
if (transaction === undefined) {
return {
success: false,
statusCode: 400,
response: 'transaction is undefined'
}
}
const serializedTransaction = '0x' + (await transaction).serialize().toString('hex')
const transactionHash = await web3.eth.sendSignedTransaction(serializedTransaction, function (error, hash) {
if (!error) {
if (process.env.NODE_ENVIRONMENT === 'development') { log.green('Transaction sent!', hash) }
const interval = setInterval(async function () {
if (process.env.NODE_ENVIRONMENT === 'development') { console.log('Attempting to get transaction receipt...') }
await web3.eth.getTransactionReceipt(hash, function (err, rec) {
if (rec) {
log.green('Receipt received!')
clearInterval(interval)
}
if (err) { console.log(err) }
})
}, 2500)
} else {
if (process.env.NODE_ENVIRONMENT === 'development') { console.log('Something went wrong while submitting your transaction:', error) }
}
})
if (process.env.NODE_ENVIRONMENT === 'development') { log.cyan('Send Transaction ---- Complete') }
return {
success: true,
statusCode: 200,
response: {
transactionHash: transactionHash.transactionHash,
rawData: transactionHash
}
}
} catch (error) {
console.log(error)
return {
success: false,
statusCode: 400,
response: transaction
}
}
}