-
Notifications
You must be signed in to change notification settings - Fork 175
/
fixtures.go
328 lines (276 loc) · 8.83 KB
/
fixtures.go
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package testutil
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"strings"
"testing"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/rs/zerolog"
"github.com/stretchr/testify/require"
"github.com/onflow/flow-go/crypto"
"github.com/onflow/flow-go/crypto/hash"
"github.com/onflow/flow-go/engine/execution/utils"
"github.com/onflow/flow-go/fvm"
"github.com/onflow/flow-go/fvm/programs"
"github.com/onflow/flow-go/fvm/state"
fvmUtils "github.com/onflow/flow-go/fvm/utils"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/utils/unittest"
)
func CreateContractDeploymentTransaction(contractName string, contract string, authorizer flow.Address, chain flow.Chain) *flow.TransactionBody {
encoded := hex.EncodeToString([]byte(contract))
return flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(`transaction {
prepare(signer: AuthAccount, service: AuthAccount) {
signer.contracts.add(name: "%s", code: "%s".decodeHex())
}
}`, contractName, encoded)),
).
AddAuthorizer(authorizer).
AddAuthorizer(chain.ServiceAddress())
}
func UpdateContractDeploymentTransaction(contractName string, contract string, authorizer flow.Address, chain flow.Chain) *flow.TransactionBody {
encoded := hex.EncodeToString([]byte(contract))
return flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(`transaction {
prepare(signer: AuthAccount, service: AuthAccount) {
signer.contracts.update__experimental(name: "%s", code: "%s".decodeHex())
}
}`, contractName, encoded)),
).
AddAuthorizer(authorizer).
AddAuthorizer(chain.ServiceAddress())
}
func CreateUnauthorizedContractDeploymentTransaction(contractName string, contract string, authorizer flow.Address) *flow.TransactionBody {
encoded := hex.EncodeToString([]byte(contract))
return flow.NewTransactionBody().
SetScript([]byte(fmt.Sprintf(`transaction {
prepare(signer: AuthAccount) {
signer.contracts.add(name: "%s", code: "%s".decodeHex())
}
}`, contractName, encoded)),
).
AddAuthorizer(authorizer)
}
func SignPayload(
tx *flow.TransactionBody,
account flow.Address,
privateKey flow.AccountPrivateKey,
) error {
hasher, err := utils.NewHasher(privateKey.HashAlgo)
if err != nil {
return fmt.Errorf("failed to create hasher: %w", err)
}
err = tx.SignPayload(account, 0, privateKey.PrivateKey, hasher)
if err != nil {
return fmt.Errorf("failed to sign transaction: %w", err)
}
return nil
}
func SignEnvelope(tx *flow.TransactionBody, account flow.Address, privateKey flow.AccountPrivateKey) error {
hasher, err := utils.NewHasher(privateKey.HashAlgo)
if err != nil {
return fmt.Errorf("failed to create hasher: %w", err)
}
err = tx.SignEnvelope(account, 0, privateKey.PrivateKey, hasher)
if err != nil {
return fmt.Errorf("failed to sign transaction: %w", err)
}
return nil
}
func SignTransaction(
tx *flow.TransactionBody,
address flow.Address,
privateKey flow.AccountPrivateKey,
seqNum uint64,
) error {
tx.SetProposalKey(address, 0, seqNum)
tx.SetPayer(address)
return SignEnvelope(tx, address, privateKey)
}
func SignTransactionAsServiceAccount(tx *flow.TransactionBody, seqNum uint64, chain flow.Chain) error {
return SignTransaction(tx, chain.ServiceAddress(), unittest.ServiceAccountPrivateKey, seqNum)
}
// GenerateAccountPrivateKeys generates a number of private keys.
func GenerateAccountPrivateKeys(numberOfPrivateKeys int) ([]flow.AccountPrivateKey, error) {
var privateKeys []flow.AccountPrivateKey
for i := 0; i < numberOfPrivateKeys; i++ {
pk, err := GenerateAccountPrivateKey()
if err != nil {
return nil, err
}
privateKeys = append(privateKeys, pk)
}
return privateKeys, nil
}
// GenerateAccountPrivateKey generates a private key.
func GenerateAccountPrivateKey() (flow.AccountPrivateKey, error) {
seed := make([]byte, crypto.KeyGenSeedMinLenECDSAP256)
_, err := rand.Read(seed)
if err != nil {
return flow.AccountPrivateKey{}, err
}
privateKey, err := crypto.GeneratePrivateKey(crypto.ECDSAP256, seed)
if err != nil {
return flow.AccountPrivateKey{}, err
}
pk := flow.AccountPrivateKey{
PrivateKey: privateKey,
SignAlgo: crypto.ECDSAP256,
HashAlgo: hash.SHA2_256,
}
return pk, nil
}
// CreateAccounts inserts accounts into the ledger using the provided private keys.
func CreateAccounts(
vm *fvm.VirtualMachine,
view state.View,
programs *programs.Programs,
privateKeys []flow.AccountPrivateKey,
chain flow.Chain,
) ([]flow.Address, error) {
return CreateAccountsWithSimpleAddresses(vm, view, programs, privateKeys, chain)
}
func CreateAccountsWithSimpleAddresses(
vm *fvm.VirtualMachine,
view state.View,
programs *programs.Programs,
privateKeys []flow.AccountPrivateKey,
chain flow.Chain,
) ([]flow.Address, error) {
ctx := fvm.NewContext(
zerolog.Nop(),
fvm.WithChain(chain),
fvm.WithTransactionProcessors(
fvm.NewTransactionInvocator(zerolog.Nop()),
),
)
var accounts []flow.Address
script := []byte(`
transaction(publicKey: [UInt8]) {
prepare(signer: AuthAccount) {
let acct = AuthAccount(payer: signer)
acct.addPublicKey(publicKey)
}
}
`)
serviceAddress := chain.ServiceAddress()
for i, privateKey := range privateKeys {
accountKey := privateKey.PublicKey(fvm.AccountKeyWeightThreshold)
encAccountKey, _ := flow.EncodeRuntimeAccountPublicKey(accountKey)
cadAccountKey := BytesToCadenceArray(encAccountKey)
encCadAccountKey, _ := jsoncdc.Encode(cadAccountKey)
txBody := flow.NewTransactionBody().
SetScript(script).
AddArgument(encCadAccountKey).
AddAuthorizer(serviceAddress)
tx := fvm.Transaction(txBody, uint32(i))
err := vm.Run(ctx, tx, view, programs)
if err != nil {
return nil, err
}
if tx.Err != nil {
return nil, fmt.Errorf("failed to create account: %w", tx.Err)
}
var addr flow.Address
for _, event := range tx.Events {
if event.Type == flow.EventAccountCreated {
data, err := jsoncdc.Decode(event.Payload)
if err != nil {
return nil, errors.New("error decoding events")
}
addr = flow.Address(data.(cadence.Event).Fields[0].(cadence.Address))
break
}
}
if addr == flow.EmptyAddress {
return nil, errors.New("no account creation event emitted")
}
accounts = append(accounts, addr)
}
return accounts, nil
}
func RootBootstrappedLedger(vm *fvm.VirtualMachine, ctx fvm.Context) state.View {
view := fvmUtils.NewSimpleView()
programs := programs.NewEmptyPrograms()
bootstrap := fvm.Bootstrap(
unittest.ServiceAccountPublicKey,
fvm.WithInitialTokenSupply(unittest.GenesisTokenSupply),
)
_ = vm.Run(
ctx,
bootstrap,
view,
programs,
)
return view
}
func BytesToCadenceArray(l []byte) cadence.Array {
values := make([]cadence.Value, len(l))
for i, b := range l {
values[i] = cadence.NewUInt8(b)
}
return cadence.NewArray(values)
}
// CreateAccountCreationTransaction creates a transaction which will create a new account.
//
// This function returns a randomly generated private key and the transaction.
func CreateAccountCreationTransaction(t *testing.T, chain flow.Chain) (flow.AccountPrivateKey, *flow.TransactionBody) {
accountKey, err := GenerateAccountPrivateKey()
require.NoError(t, err)
keyBytes, err := flow.EncodeRuntimeAccountPublicKey(accountKey.PublicKey(1000))
require.NoError(t, err)
// define the cadence script
script := fmt.Sprintf(`
transaction {
prepare(signer: AuthAccount) {
let acct = AuthAccount(payer: signer)
acct.addPublicKey("%s".decodeHex())
}
}
`, hex.EncodeToString(keyBytes))
// create the transaction to create the account
tx := flow.NewTransactionBody().
SetScript([]byte(script)).
AddAuthorizer(chain.ServiceAddress())
return accountKey, tx
}
// CreateAddAccountKeyTransaction generates a tx that adds a key to an account.
func CreateAddAccountKeyTransaction(t *testing.T, accountKey *flow.AccountPrivateKey) *flow.TransactionBody {
keyBytes, err := flow.EncodeRuntimeAccountPublicKey(accountKey.PublicKey(1000))
require.NoError(t, err)
// encode the bytes to cadence string
encodedKey := languageEncodeBytes(keyBytes)
script := fmt.Sprintf(`
transaction {
prepare(signer: AuthAccount) {
signer.addPublicKey(%s)
}
}
`, encodedKey)
return &flow.TransactionBody{
Script: []byte(script),
}
}
// CreateRemoveAccountKeyTransaction generates a tx that removes a key from an account.
func CreateRemoveAccountKeyTransaction(index int) *flow.TransactionBody {
script := fmt.Sprintf(`
transaction {
prepare(signer: AuthAccount) {
signer.removePublicKey(%d)
}
}
`, index)
return &flow.TransactionBody{
Script: []byte(script),
}
}
func languageEncodeBytes(b []byte) string {
if len(b) == 0 {
return "[]"
}
return strings.Join(strings.Fields(fmt.Sprintf("%d", b)), ",")
}