How to use WithBody method of wait Package

Best Testcontainers-go code snippet using wait.WithBody

e2e_test.go

Source:e2e_test.go Github

copy

Full Screen

...95 body := new(protocol.AcmeFaucet)96 body.Url = senderUrl97 send(acctesting.NewTransaction().98 WithPrincipal(protocol.FaucetUrl.RootIdentity()).99 WithBody(body).100 Faucet())101 })102 batch := n.db.Begin(true)103 //acme to credits @ $0.05 acme price is 1:5104 liteTokenId := senderUrl.RootIdentity()105 n.Require().NoError(acctesting.AddCredits(batch, liteTokenId, credits))106 n.require.NoError(batch.Commit())107 balance := map[*url.URL]int64{}108 for i := 0; i < M; i++ {109 n.MustExecuteAndWait(func(send func(*Tx)) {110 for i := 0; i < N; i++ {111 recipient := recipients[rand.Intn(len(recipients))]112 balance[recipient] += 1000113 exch := new(protocol.SendTokens)114 exch.AddRecipient(recipient, big.NewInt(int64(1000)))115 send(newTxn(senderUrl.String()).116 WithBody(exch).117 Initiate(protocol.SignatureTypeLegacyED25519, sender).118 Build())119 }120 })121 }122 return senderUrl.String(), balance123}124func TestFaucet(t *testing.T) {125 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)126 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)127 n := nodes[partitions[1]][0]128 alice := generateKey()129 aliceUrl := acctesting.AcmeLiteAddressTmPriv(alice)130 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {131 body := new(protocol.AcmeFaucet)132 body.Url = aliceUrl133 faucet := protocol.Faucet.Signer()134 send(acctesting.NewTransaction().135 WithPrincipal(protocol.FaucetUrl).136 WithTimestamp(faucet.Timestamp()).137 WithBody(body).138 Faucet())139 })140 require.Equal(t, int64(protocol.AcmeFaucetAmount*protocol.AcmePrecision), n.GetLiteTokenAccount(aliceUrl.String()).Balance.Int64())141}142func TestAnchorChain(t *testing.T) {143 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)144 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)145 n := nodes[partitions[1]][0]146 liteAccount := generateKey()147 newAdi := generateKey()148 keyHash := sha256.Sum256(newAdi.PubKey().Address())149 batch := n.db.Begin(true)150 require.NoError(n.t, acctesting.CreateLiteTokenAccountWithCredits(batch, liteAccount, protocol.AcmeFaucetAmount, 1e6))151 require.NoError(t, batch.Commit())152 n.MustExecuteAndWait(func(send func(*Tx)) {153 adi := new(protocol.CreateIdentity)154 adi.Url = protocol.AccountUrl("RoadRunner")155 var err error156 adi.KeyBookUrl, err = url.Parse(fmt.Sprintf("%s/book", adi.Url))157 require.NoError(t, err)158 adi.KeyHash = keyHash[:]159 sponsorUrl := acctesting.AcmeLiteAddressTmPriv(liteAccount).RootIdentity().String()160 send(newTxn(sponsorUrl).161 WithBody(adi).162 Initiate(protocol.SignatureTypeLegacyED25519, liteAccount).163 Build())164 })165 // Sanity check166 require.Equal(t, "acc://RoadRunner.acme", n.GetADI("RoadRunner").Url.String())167 // // Get the anchor chain manager168 // batch = n.db.Begin(true)169 // defer batch.Discard()170 // ledger := batch.Account(n.network.NodeUrl(protocol.Ledger))171 // // Check each anchor172 // // TODO FIX This is broken because the ledger no longer has a list of updates173 // var ledgerState *protocol.InternalLedger174 // require.NoError(t, ledger.GetStateAs(&ledgerState))175 // rootChain, err := ledger.MinorRootChain().Get()176 // require.NoError(t, err)177 // first := rootChain.Height() - int64(len(ledgerState.Updates))178 // for i, meta := range ledgerState.Updates {179 // root, err := rootChain.Entry(first + int64(i))180 // require.NoError(t, err)181 // if meta.Name == "bpt" {182 // assert.Equal(t, root, batch.BptRootHash(), "wrong anchor for BPT")183 // continue184 // }185 // mgr, err := batch.Account(meta.Account).ReadChain(meta.Name)186 // require.NoError(t, err)187 // assert.Equal(t, root, mgr.Anchor(), "wrong anchor for %s#chain/%s", meta.Account, meta.Name)188 // }189 // // TODO Once block indexing has been implemented, verify that the following chains got modified190 // assert.Subset(t, accounts, []string{191 // "acc://RoadRunner#chain/main",192 // "acc://RoadRunner#chain/pending",193 // "acc://RoadRunner/book#chain/main",194 // "acc://RoadRunner/page#chain/main",195 // })196}197func TestCreateADI(t *testing.T) {198 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)199 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)200 n := nodes[partitions[1]][0]201 liteAccount := generateKey()202 newAdi := generateKey()203 keyHash := sha256.Sum256(newAdi.PubKey().Address())204 batch := n.db.Begin(true)205 require.NoError(n.t, acctesting.CreateLiteTokenAccountWithCredits(batch, liteAccount, protocol.AcmeFaucetAmount, 1e6))206 require.NoError(t, batch.Commit())207 n.MustExecuteAndWait(func(send func(*Tx)) {208 adi := new(protocol.CreateIdentity)209 adi.Url = protocol.AccountUrl("RoadRunner")210 adi.KeyHash = keyHash[:]211 var err error212 adi.KeyBookUrl, err = url.Parse(fmt.Sprintf("%s/foo-book", adi.Url))213 require.NoError(t, err)214 sponsorUrl := acctesting.AcmeLiteAddressTmPriv(liteAccount).RootIdentity().String()215 send(newTxn(sponsorUrl).216 WithBody(adi).217 Initiate(protocol.SignatureTypeLegacyED25519, liteAccount).218 Build())219 })220 r := n.GetADI("RoadRunner")221 require.Equal(t, "acc://RoadRunner.acme", r.Url.String())222 kg := n.GetKeyBook("RoadRunner/foo-book")223 require.Equal(t, uint64(1), kg.PageCount)224 ks := n.GetKeyPage("RoadRunner/foo-book/1")225 require.Len(t, ks.Keys, 1)226 require.Equal(t, keyHash[:], ks.Keys[0].PublicKeyHash)227}228func TestAdiUrlLengthLimit(t *testing.T) {229 check := newDefaultCheckError(t, false)230 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)231 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())232 n := nodes[partitions[1]][0]233 liteAccount := generateKey()234 newAdi := generateKey()235 keyHash := sha256.Sum256(newAdi.PubKey().Address())236 batch := n.db.Begin(true)237 require.NoError(n.t, acctesting.CreateLiteTokenAccountWithCredits(batch, liteAccount, protocol.AcmeFaucetAmount, 1e6))238 require.NoError(t, batch.Commit())239 accurl := strings.Repeat("𒀹", 250) // 𒀹 is 4 bytes240 txn := n.MustExecuteAndWait(func(send func(*Tx)) {241 adi := new(protocol.CreateIdentity)242 adi.Url = protocol.AccountUrl(accurl)243 adi.KeyHash = keyHash[:]244 var err error245 adi.KeyBookUrl, err = url.Parse(fmt.Sprintf("%s/foo-book", adi.Url))246 require.NoError(t, err)247 sponsorUrl := acctesting.AcmeLiteAddressTmPriv(liteAccount).RootIdentity().String()248 send(newTxn(sponsorUrl).249 WithBody(adi).250 Initiate(protocol.SignatureTypeLegacyED25519, liteAccount).251 Build())252 })253 res, err := n.QueryTx(txn[0][:], time.Second, true)254 require.NoError(t, err)255 h := res.Produced[0].Hash()256 res, err = n.QueryTx(h[:], time.Second, true)257 require.NoError(t, err)258 require.Equal(t, errors.StatusBadUrlLength, res.Status.Code)259}260func TestCreateADIWithoutKeybook(t *testing.T) {261 check := newDefaultCheckError(t, false)262 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)263 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())264 n := nodes[partitions[1]][0]265 liteAccount := generateKey()266 newAdi := generateKey()267 keyHash := sha256.Sum256(newAdi.PubKey().Address())268 batch := n.db.Begin(true)269 require.NoError(n.t, acctesting.CreateLiteTokenAccountWithCredits(batch, liteAccount, protocol.AcmeFaucetAmount, 1e6))270 require.NoError(t, batch.Commit())271 _, _, err := n.Execute(func(send func(*Tx)) {272 adi := new(protocol.CreateIdentity)273 adi.Url = protocol.AccountUrl("RoadRunner")274 adi.KeyHash = keyHash[:]275 sponsorUrl := acctesting.AcmeLiteAddressTmPriv(liteAccount).String()276 send(newTxn(sponsorUrl).277 WithBody(adi).278 Initiate(protocol.SignatureTypeLegacyED25519, liteAccount).279 Build())280 })281 require.Error(t, err)282}283func TestCreateLiteDataAccount(t *testing.T) {284 //this test exercises WriteDataTo and SyntheticWriteData validators285 firstEntry := protocol.AccumulateDataEntry{}286 firstEntry.Data = append(firstEntry.Data, []byte{})287 firstEntry.Data = append(firstEntry.Data, []byte("Factom PRO"))288 firstEntry.Data = append(firstEntry.Data, []byte("Tutorial"))289 //create a lite data account aka factom chainId290 chainId := protocol.ComputeLiteDataAccountId(&firstEntry)291 liteDataAddress, err := protocol.LiteDataAddress(chainId)292 if err != nil {293 t.Fatal(err)294 }295 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)296 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)297 n := nodes[partitions[1]][0]298 adiKey := generateKey()299 batch := n.db.Begin(true)300 require.NoError(t, acctesting.CreateAdiWithCredits(batch, adiKey, "FooBar", 1e9))301 require.NoError(t, batch.Commit())302 ids := n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {303 wdt := new(protocol.WriteDataTo)304 wdt.Recipient = liteDataAddress305 wdt.Entry = &firstEntry306 send(newTxn("FooBar").307 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).308 WithBody(wdt).309 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).310 Build())311 })312 partialChainId, err := protocol.ParseLiteDataAddress(liteDataAddress)313 if err != nil {314 t.Fatal(err)315 }316 r := n.GetLiteDataAccount(liteDataAddress.String())317 require.Equal(t, liteDataAddress.String(), r.Url.String())318 require.Equal(t, partialChainId, chainId)319 firstEntryHash := firstEntry.Hash()320 batch = n.db.Begin(false)321 defer batch.Discard()322 synthIds, err := batch.Transaction(ids[0][:]).GetSyntheticTxns()323 require.NoError(t, err)324 // Verify the entry hash in the transaction result325 h := synthIds.Entries[0].Hash()326 txStatus, err := batch.Transaction(h[:]).GetStatus()327 require.NoError(t, err)328 require.IsType(t, (*protocol.WriteDataResult)(nil), txStatus.Result)329 txResult := txStatus.Result.(*protocol.WriteDataResult)330 require.Equal(t, hex.EncodeToString(firstEntryHash), hex.EncodeToString(txResult.EntryHash[:]), "Transaction result entry hash does not match")331 // Verify the entry hash returned by Entry332 entryHash, err := indexing.Data(batch, liteDataAddress).Entry(0)333 require.NoError(t, err)334 txnHash, err := indexing.Data(batch, liteDataAddress).Transaction(entryHash)335 require.NoError(t, err)336 entry, err := indexing.GetDataEntry(batch, txnHash)337 require.NoError(t, err)338 hashFromEntry := entry.Hash()339 require.Equal(t, hex.EncodeToString(firstEntryHash), hex.EncodeToString(hashFromEntry), "Chain Entry.Hash does not match")340 //sample verification for calculating the hash from lite data entry341 require.Equal(t, hex.EncodeToString(firstEntryHash), hex.EncodeToString(entryHash), "Chain GetHashes does not match")342 require.Equal(t, hex.EncodeToString(firstEntryHash), hex.EncodeToString(entry.Hash()), "Chain GetHashes does not match")343}344func TestCreateAdiDataAccount(t *testing.T) {345 t.Run("Data Account with Default Key Book and no Manager Key Book", func(t *testing.T) {346 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)347 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)348 n := nodes[partitions[1]][0]349 adiKey := generateKey()350 batch := n.db.Begin(true)351 require.NoError(t, acctesting.CreateAdiWithCredits(batch, adiKey, "FooBar", 1e9))352 require.NoError(t, batch.Commit())353 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {354 tac := new(protocol.CreateDataAccount)355 tac.Url = protocol.AccountUrl("FooBar", "oof")356 send(newTxn("FooBar").357 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).358 WithBody(tac).359 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).360 Build())361 })362 r := n.GetDataAccount("FooBar/oof")363 require.Equal(t, "acc://FooBar.acme/oof", r.Url.String())364 require.Contains(t, n.GetDirectory("FooBar"), protocol.AccountUrl("FooBar", "oof").String())365 })366 t.Run("Data Account with Custom Key Book and Manager Key Book Url", func(t *testing.T) {367 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)368 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)369 n := nodes[partitions[1]][0]370 adiKey, pageKey := generateKey(), generateKey()371 batch := n.db.Begin(true)372 require.NoError(t, acctesting.CreateAdiWithCredits(batch, adiKey, "FooBar", 1e9))373 require.NoError(t, acctesting.CreateKeyBook(batch, "acc://FooBar/foo/book1", pageKey.PubKey().Bytes()))374 require.NoError(t, acctesting.CreateKeyPage(batch, "acc://FooBar/foo/book1"))375 require.NoError(t, acctesting.CreateKeyBook(batch, "acc://FooBar/mgr/book1", nil))376 require.NoError(t, acctesting.CreateKeyPage(batch, "acc://FooBar/mgr/book1", pageKey.PubKey().Bytes()))377 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("FooBar", "foo", "book1", "1"), 1e9))378 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("FooBar", "mgr", "book1", "2"), 1e9))379 require.NoError(t, batch.Commit())380 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {381 cda := new(protocol.CreateDataAccount)382 cda.Url = protocol.AccountUrl("FooBar", "oof")383 cda.Authorities = []*url.URL{384 protocol.AccountUrl("FooBar", "foo", "book1"),385 protocol.AccountUrl("FooBar", "mgr", "book1"),386 }387 send(newTxn("FooBar").388 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).389 WithBody(cda).390 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).391 WithSigner(protocol.AccountUrl("FooBar", "foo", "book1", "1"), 1).392 Sign(protocol.SignatureTypeED25519, pageKey).393 WithSigner(protocol.AccountUrl("FooBar", "mgr", "book1", "2"), 1).394 Sign(protocol.SignatureTypeED25519, pageKey).395 Build())396 })397 u := protocol.AccountUrl("FooBar", "foo", "book1")398 r := n.GetDataAccount("FooBar/oof")399 require.Equal(t, "acc://FooBar.acme/oof", r.Url.String())400 require.Equal(t, "acc://FooBar.acme/mgr/book1", r.ManagerKeyBook().String())401 require.Equal(t, u.String(), r.KeyBook().String())402 })403 t.Run("Data Account data entry", func(t *testing.T) {404 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)405 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)406 n := nodes[partitions[1]][0]407 adiKey := generateKey()408 batch := n.db.Begin(true)409 require.NoError(t, acctesting.CreateAdiWithCredits(batch, adiKey, "FooBar", 1e9))410 require.NoError(t, batch.Commit())411 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {412 tac := new(protocol.CreateDataAccount)413 tac.Url = protocol.AccountUrl("FooBar", "oof")414 send(newTxn("FooBar").415 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).416 WithBody(tac).417 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).418 Build())419 })420 r := n.GetDataAccount("FooBar/oof")421 require.Equal(t, "acc://FooBar.acme/oof", r.Url.String())422 require.Contains(t, n.GetDirectory("FooBar"), protocol.AccountUrl("FooBar", "oof").String())423 wd := new(protocol.WriteData)424 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {425 entry := new(protocol.AccumulateDataEntry)426 wd.Entry = entry427 entry.Data = append(entry.Data, []byte("thequickbrownfoxjumpsoverthelazydog"))428 for i := 0; i < 10; i++ {429 entry.Data = append(entry.Data, []byte(fmt.Sprintf("test id %d", i)))430 }431 send(newTxn("FooBar/oof").432 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).433 WithBody(wd).434 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).435 Build())436 })437 // Without the sleep, this test fails on Windows and macOS438 time.Sleep(3 * time.Second)439 // Test getting the data by URL440 rde := new(query.ResponseDataEntry)441 n.QueryAccountAs("FooBar/oof#data", rde)442 if !protocol.EqualDataEntry(rde.Entry, wd.Entry) {443 t.Fatalf("data query does not match what was entered")444 }445 //now test query by entry hash.446 rde2 := new(query.ResponseDataEntry)447 n.QueryAccountAs(fmt.Sprintf("FooBar/oof#data/%X", wd.Entry.Hash()), rde2)448 if !protocol.EqualDataEntry(rde.Entry, rde2.Entry) {449 t.Fatalf("data query does not match what was entered")450 }451 //now test query by entry set452 rde3 := new(query.ResponseDataEntrySet)453 n.QueryAccountAs("FooBar/oof#data/0:1", rde3)454 if !protocol.EqualDataEntry(rde.Entry, rde3.DataEntries[0].Entry) {455 t.Fatalf("data query does not match what was entered")456 }457 })458 t.Run("Data Account data entry to scratch chain", func(t *testing.T) {459 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)460 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)461 n := nodes[partitions[1]][0]462 adiKey := generateKey()463 batch := n.db.Begin(true)464 require.NoError(t, acctesting.CreateAdiWithCredits(batch, adiKey, "FooBar", 1e9))465 require.NoError(t, batch.Commit())466 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {467 tac := new(protocol.CreateDataAccount)468 tac.Url = protocol.AccountUrl("FooBar", "scr")469 send(newTxn("FooBar").470 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).471 WithBody(tac).472 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).473 Build())474 })475 r := n.GetDataAccount("FooBar/scr")476 require.Equal(t, "acc://FooBar.acme/scr", r.Url.String())477 require.Contains(t, n.GetDirectory("FooBar"), protocol.AccountUrl("FooBar", "scr").String())478 wd := new(protocol.WriteData)479 wd.Scratch = true480 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {481 entry := new(protocol.AccumulateDataEntry)482 wd.Entry = entry483 entry.Data = append(entry.Data, []byte("thequickbrownfoxjumpsoverthelazydog"))484 for i := 0; i < 10; i++ {485 entry.Data = append(entry.Data, []byte(fmt.Sprintf("test id %d", i)))486 }487 send(newTxn("FooBar/scr").488 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).489 WithBody(wd).490 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).491 Build())492 })493 // Without the sleep, this test fails on Windows and macOS494 time.Sleep(3 * time.Second)495 // Test getting the data by URL496 rde := new(query.ResponseDataEntry)497 n.QueryAccountAs("FooBar/scr#data", rde)498 if !protocol.EqualDataEntry(rde.Entry, wd.Entry) {499 t.Fatalf("data query does not match what was entered")500 }501 //now test query by entry hash.502 rde2 := new(query.ResponseDataEntry)503 n.QueryAccountAs(fmt.Sprintf("FooBar/scr#data/%X", wd.Entry.Hash()), rde2)504 if !protocol.EqualDataEntry(rde.Entry, rde2.Entry) {505 t.Fatalf("data query does not match what was entered")506 }507 //now test query by entry set508 rde3 := new(query.ResponseDataEntrySet)509 n.QueryAccountAs("FooBar/scr#data/0:1", rde3)510 if !protocol.EqualDataEntry(rde.Entry, rde3.DataEntries[0].Entry) {511 t.Fatalf("data query does not match what was entered")512 }513 })514}515func TestCreateAdiTokenAccount(t *testing.T) {516 t.Run("Default Key Book", func(t *testing.T) {517 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)518 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)519 n := nodes[partitions[1]][0]520 adiKey := generateKey()521 batch := n.db.Begin(true)522 require.NoError(t, acctesting.CreateAdiWithCredits(batch, adiKey, "FooBar", 1e9))523 require.NoError(t, batch.Commit())524 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {525 tac := new(protocol.CreateTokenAccount)526 tac.Url = protocol.AccountUrl("FooBar", "Baz")527 tac.TokenUrl = protocol.AcmeUrl()528 send(newTxn("FooBar").529 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).530 WithBody(tac).531 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).532 Build())533 })534 r := n.GetTokenAccount("FooBar/Baz")535 require.Equal(t, "acc://FooBar.acme/Baz", r.Url.String())536 require.Equal(t, protocol.AcmeUrl().String(), r.TokenUrl.String())537 require.ElementsMatch(t, []string{538 protocol.AccountUrl("FooBar", "book0").String(),539 protocol.AccountUrl("FooBar", "book0", "1").String(),540 protocol.AccountUrl("FooBar", "Baz").String(),541 }, n.GetDirectory("FooBar"))542 })543 t.Run("Custom Key Book", func(t *testing.T) {544 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)545 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)546 n := nodes[partitions[1]][0]547 adiKey, pageKey := generateKey(), generateKey()548 batch := n.db.Begin(true)549 require.NoError(t, acctesting.CreateAdiWithCredits(batch, adiKey, "FooBar", 1e9))550 require.NoError(t, acctesting.CreateKeyBook(batch, "FooBar/book1", pageKey.PubKey().Bytes()))551 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("FooBar", "book1", "1"), 1e9))552 require.NoError(t, batch.Commit())553 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {554 tac := new(protocol.CreateTokenAccount)555 tac.Url = protocol.AccountUrl("FooBar", "Baz")556 tac.TokenUrl = protocol.AcmeUrl()557 tac.Authorities = []*url.URL{protocol.AccountUrl("FooBar", "book1")}558 send(newTxn("FooBar").559 WithSigner(protocol.AccountUrl("FooBar", "book0", "1"), 1).560 WithBody(tac).561 Initiate(protocol.SignatureTypeLegacyED25519, adiKey).562 WithSigner(protocol.AccountUrl("FooBar", "book1", "1"), 1).563 Sign(protocol.SignatureTypeED25519, pageKey).564 Build())565 })566 })567 t.Run("Remote Key Book", func(t *testing.T) {568 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)569 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)570 n := nodes[partitions[1]][0]571 aliceKey, bobKey := generateKey(), generateKey()572 batch := n.db.Begin(true)573 require.NoError(t, acctesting.CreateAdiWithCredits(batch, aliceKey, "alice", 1e9))574 require.NoError(t, acctesting.CreateAdiWithCredits(batch, bobKey, "bob", 1e9))575 require.NoError(t, batch.Commit())576 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {577 tac := new(protocol.CreateTokenAccount)578 tac.Url = protocol.AccountUrl("alice", "tokens")579 tac.TokenUrl = protocol.AcmeUrl()580 tac.Authorities = []*url.URL{protocol.AccountUrl("bob", "book0")}581 send(newTxn("alice").582 WithSigner(protocol.AccountUrl("alice", "book0", "1"), 1).583 WithBody(tac).584 Initiate(protocol.SignatureTypeLegacyED25519, aliceKey).585 WithSigner(protocol.AccountUrl("bob", "book0", "1"), 1).586 Sign(protocol.SignatureTypeED25519, bobKey).587 Build())588 })589 // Wait for the remote signature to settle590 time.Sleep(time.Second)591 r := n.GetTokenAccount("alice/tokens")592 require.Equal(t, "alice.acme/tokens", r.Url.ShortString())593 require.Equal(t, protocol.AcmeUrl().String(), r.TokenUrl.String())594 require.Equal(t, "bob.acme/book0", r.KeyBook().ShortString())595 })596}597func TestLiteAccountTx(t *testing.T) {598 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)599 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)600 n := nodes[partitions[1]][0]601 alice, bob, charlie := generateKey(), generateKey(), generateKey()602 batch := n.db.Begin(true)603 require.NoError(n.t, acctesting.CreateLiteTokenAccountWithCredits(batch, alice, protocol.AcmeFaucetAmount, 1e9))604 require.NoError(n.t, acctesting.CreateLiteTokenAccount(batch, bob, 0))605 require.NoError(n.t, acctesting.CreateLiteTokenAccount(batch, charlie, 0))606 require.NoError(t, batch.Commit())607 aliceUrl := acctesting.AcmeLiteAddressTmPriv(alice)608 bobUrl := acctesting.AcmeLiteAddressTmPriv(bob)609 charlieUrl := acctesting.AcmeLiteAddressTmPriv(charlie)610 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {611 exch := new(protocol.SendTokens)612 exch.AddRecipient(bobUrl, big.NewInt(int64(1000)))613 exch.AddRecipient(charlieUrl, big.NewInt(int64(2000)))614 send(newTxn(aliceUrl.String()).615 WithSigner(aliceUrl.RootIdentity(), 1).616 WithBody(exch).617 Initiate(protocol.SignatureTypeLegacyED25519, alice).618 Build())619 })620 require.Equal(t, int64(protocol.AcmeFaucetAmount*protocol.AcmePrecision-3000), n.GetLiteTokenAccount(aliceUrl.String()).Balance.Int64())621 require.Equal(t, int64(1000), n.GetLiteTokenAccount(bobUrl.String()).Balance.Int64())622 require.Equal(t, int64(2000), n.GetLiteTokenAccount(charlieUrl.String()).Balance.Int64())623}624func TestAdiAccountTx(t *testing.T) {625 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)626 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)627 n := nodes[partitions[1]][0]628 fooKey, barKey := generateKey(), generateKey()629 batch := n.db.Begin(true)630 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))631 require.NoError(t, acctesting.CreateTokenAccount(batch, "foo/tokens", protocol.AcmeUrl().String(), 1, false))632 require.NoError(t, acctesting.CreateADI(batch, barKey, "bar"))633 require.NoError(t, acctesting.CreateTokenAccount(batch, "bar/tokens", protocol.AcmeUrl().String(), 0, false))634 require.NoError(t, batch.Commit())635 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {636 exch := new(protocol.SendTokens)637 exch.AddRecipient(protocol.AccountUrl("bar", "tokens"), big.NewInt(int64(68)))638 send(newTxn("foo/tokens").639 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).640 WithBody(exch).641 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).642 Build())643 })644 require.Equal(t, int64(protocol.AcmePrecision-68), n.GetTokenAccount("foo/tokens").Balance.Int64())645 require.Equal(t, int64(68), n.GetTokenAccount("bar/tokens").Balance.Int64())646}647func TestSendTokensToBadRecipient(t *testing.T) {648 check := newDefaultCheckError(t, false)649 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)650 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())651 n := nodes[partitions[1]][0]652 alice := generateKey()653 aliceUrl := acctesting.AcmeLiteAddressTmPriv(alice)654 batch := n.db.Begin(true)655 require.NoError(n.t, acctesting.CreateLiteTokenAccountWithCredits(batch, alice, protocol.AcmeFaucetAmount, 1e9))656 require.NoError(t, batch.Commit())657 // The send should succeed658 txnHashes := n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {659 exch := new(protocol.SendTokens)660 exch.AddRecipient(protocol.AccountUrl("foo"), big.NewInt(int64(1000)))661 send(newTxn(aliceUrl.String()).662 WithSigner(aliceUrl.RootIdentity(), 1).663 WithBody(exch).664 Initiate(protocol.SignatureTypeLegacyED25519, alice).665 Build())666 })667 // The synthetic transaction should fail668 res, err := n.QueryTx(txnHashes[0][:], time.Second, true)669 require.NoError(t, err)670 h := res.Produced[0].Hash()671 res, err = n.QueryTx(h[:], time.Second, true)672 require.NoError(t, err)673 require.Equal(t, errors.StatusNotFound, res.Status.Code)674 // Give the synthetic receipt a second to resolve - workaround AC-1238675 time.Sleep(time.Second)676 // The balance should be unchanged677 require.Equal(t, int64(protocol.AcmeFaucetAmount*protocol.AcmePrecision), n.GetLiteTokenAccount(aliceUrl.String()).Balance.Int64())678}679func TestCreateKeyPage(t *testing.T) {680 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)681 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)682 n := nodes[partitions[1]][0]683 fooKey, testKey := generateKey(), generateKey()684 fkh := sha256.Sum256(fooKey.PubKey().Bytes())685 tkh := sha256.Sum256(testKey.PubKey().Bytes())686 batch := n.db.Begin(true)687 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))688 require.NoError(t, batch.Commit())689 page := n.GetKeyPage("foo/book0/1")690 require.Len(t, page.Keys, 1)691 key := page.Keys[0]692 require.Equal(t, uint64(0), key.LastUsedOn)693 require.Equal(t, fkh[:], key.PublicKeyHash)694 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {695 cms := new(protocol.CreateKeyPage)696 cms.Keys = append(cms.Keys, &protocol.KeySpecParams{697 KeyHash: tkh[:],698 })699 send(newTxn("foo/book0").700 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).701 WithBody(cms).702 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).703 Build())704 })705 page = n.GetKeyPage("foo/book0/2")706 require.Len(t, page.Keys, 1)707 key = page.Keys[0]708 require.Equal(t, uint64(0), key.LastUsedOn)709 require.Equal(t, tkh[:], key.PublicKeyHash)710}711func TestCreateKeyBook(t *testing.T) {712 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)713 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)714 n := nodes[partitions[1]][0]715 fooKey, testKey := generateKey(), generateKey()716 batch := n.db.Begin(true)717 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))718 require.NoError(t, batch.Commit())719 bookUrl := protocol.AccountUrl("foo", "book1")720 pageUrl := protocol.AccountUrl("foo", "book1", "1")721 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {722 csg := new(protocol.CreateKeyBook)723 csg.Url = protocol.AccountUrl("foo", "book1")724 csg.PublicKeyHash = testKey.PubKey().Bytes()725 send(newTxn("foo").726 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).727 WithBody(csg).728 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).729 Build())730 })731 book := n.GetKeyBook("foo/book1")732 require.Equal(t, uint64(1), book.PageCount)733 require.Equal(t, bookUrl, book.Url)734 page := n.GetKeyPage("foo/book1/1")735 require.Equal(t, pageUrl, page.Url)736}737func TestAddKeyPage(t *testing.T) {738 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)739 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)740 n := nodes[partitions[1]][0]741 fooKey, testKey1, testKey2 := generateKey(), generateKey(), generateKey()742 batch := n.db.Begin(true)743 require.NoError(t, acctesting.CreateADI(batch, fooKey, "foo"))744 require.NoError(t, acctesting.CreateKeyBook(batch, "foo/book1", testKey1.PubKey().Bytes()))745 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("foo", "book1", "1"), 1e9))746 require.NoError(t, batch.Commit())747 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {748 cms := new(protocol.CreateKeyPage)749 cms.Keys = append(cms.Keys, &protocol.KeySpecParams{750 KeyHash: testKey2.PubKey().Bytes(),751 })752 send(newTxn("foo/book1").753 WithSigner(protocol.AccountUrl("foo", "book1", "1"), 1).754 WithBody(cms).755 Initiate(protocol.SignatureTypeLegacyED25519, testKey1).756 Build())757 })758 page := n.GetKeyPage("foo/book1/2")759 require.Len(t, page.Keys, 1)760 key := page.Keys[0]761 require.Equal(t, uint64(0), key.LastUsedOn)762 require.Equal(t, testKey2.PubKey().Bytes(), key.PublicKeyHash)763}764func TestAddKey(t *testing.T) {765 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)766 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)767 n := nodes[partitions[1]][0]768 fooKey, testKey := generateKey(), generateKey()769 batch := n.db.Begin(true)770 require.NoError(t, acctesting.CreateADI(batch, fooKey, "foo"))771 require.NoError(t, acctesting.CreateKeyBook(batch, "foo/book1", testKey.PubKey().Bytes()))772 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("foo", "book1", "1"), 1e9))773 require.NoError(t, batch.Commit())774 newKey := generateKey()775 nkh := sha256.Sum256(newKey.PubKey().Bytes())776 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {777 op := new(protocol.AddKeyOperation)778 op.Entry.KeyHash = nkh[:]779 body := new(protocol.UpdateKeyPage)780 body.Operation = append(body.Operation, op)781 send(newTxn("foo/book1/1").782 WithSigner(protocol.AccountUrl("foo", "book1", "1"), 1).783 WithBody(body).784 Initiate(protocol.SignatureTypeLegacyED25519, testKey).785 Build())786 })787 page := n.GetKeyPage("foo/book1/1")788 require.Len(t, page.Keys, 2)789 //look for the key.790 _, _, found := page.EntryByKeyHash(nkh[:])791 require.True(t, found, "key not found in page")792}793func TestUpdateKeyPage(t *testing.T) {794 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)795 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)796 n := nodes[partitions[1]][0]797 fooKey, testKey := generateKey(), generateKey()798 batch := n.db.Begin(true)799 require.NoError(t, acctesting.CreateADI(batch, fooKey, "foo"))800 require.NoError(t, acctesting.CreateKeyBook(batch, "foo/book1", testKey.PubKey().Bytes()))801 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("foo", "book1", "1"), 1e9))802 require.NoError(t, batch.Commit())803 newKey := generateKey()804 kh := sha256.Sum256(testKey.PubKey().Bytes())805 nkh := sha256.Sum256(newKey.PubKey().Bytes())806 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {807 op := new(protocol.UpdateKeyOperation)808 op.OldEntry.KeyHash = kh[:]809 op.NewEntry.KeyHash = nkh[:]810 body := new(protocol.UpdateKeyPage)811 body.Operation = append(body.Operation, op)812 send(newTxn("foo/book1/1").813 WithSigner(protocol.AccountUrl("foo", "book1", "1"), 1).814 WithBody(body).815 Initiate(protocol.SignatureTypeLegacyED25519, testKey).816 Build())817 })818 page := n.GetKeyPage("foo/book1/1")819 require.Len(t, page.Keys, 1)820 require.Equal(t, nkh[:], page.Keys[0].PublicKeyHash)821}822func TestUpdateKey(t *testing.T) {823 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)824 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)825 n := nodes[partitions[1]][0]826 fooKey, testKey, newKey := generateKey(), generateKey(), generateKey()827 newKeyHash := sha256.Sum256(newKey.PubKey().Bytes())828 testKeyHash := sha256.Sum256(testKey.PubKey().Bytes())829 _ = testKeyHash830 // UpdateKey should always be single-sig, so set the threshold to 2 and831 // ensure the transaction still succeeds.832 batch := n.db.Begin(true)833 defer batch.Discard()834 require.NoError(t, acctesting.CreateADI(batch, fooKey, "foo"))835 require.NoError(t, acctesting.CreateKeyBook(batch, "foo/book1", testKey.PubKey().Bytes()))836 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("foo", "book1", "1"), 1e9))837 require.NoError(t, acctesting.UpdateKeyPage(batch, protocol.AccountUrl("foo", "book1", "1"), func(p *protocol.KeyPage) { p.AcceptThreshold = 2 }))838 require.NoError(t, batch.Commit())839 spec := n.GetKeyPage("foo/book1/1")840 require.Len(t, spec.Keys, 1)841 require.Equal(t, testKeyHash[:], spec.Keys[0].PublicKeyHash)842 txnHashes := n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {843 body := new(protocol.UpdateKey)844 body.NewKeyHash = newKeyHash[:]845 send(newTxn("foo/book1/1").846 WithBody(body).847 WithSigner(protocol.AccountUrl("foo", "book1", "1"), 1).848 Initiate(protocol.SignatureTypeLegacyED25519, testKey).849 Build())850 })851 batch = n.db.Begin(false)852 defer batch.Discard()853 status, err := batch.Transaction(txnHashes[0][:]).GetStatus()854 require.NoError(t, err)855 require.False(t, status.Pending(), "Transaction is still pending")856 spec = n.GetKeyPage("foo/book1/1")857 require.Len(t, spec.Keys, 1)858 require.Equal(t, newKeyHash[:], spec.Keys[0].PublicKeyHash)859}860func TestRemoveKey(t *testing.T) {861 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)862 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)863 n := nodes[partitions[1]][0]864 fooKey, testKey1, testKey2 := generateKey(), generateKey(), generateKey()865 batch := n.db.Begin(true)866 require.NoError(t, acctesting.CreateADI(batch, fooKey, "foo"))867 require.NoError(t, acctesting.CreateKeyBook(batch, "foo/book1", testKey1.PubKey().Bytes()))868 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("foo", "book1", "1"), 1e9))869 require.NoError(t, batch.Commit())870 h2 := sha256.Sum256(testKey2.PubKey().Bytes())871 // Add second key because CreateKeyBook can't do it872 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {873 op := new(protocol.AddKeyOperation)874 op.Entry.KeyHash = h2[:]875 body := new(protocol.UpdateKeyPage)876 body.Operation = append(body.Operation, op)877 send(newTxn("foo/book1/1").878 WithSigner(protocol.AccountUrl("foo", "book1", "1"), 1).879 WithBody(body).880 Initiate(protocol.SignatureTypeLegacyED25519, testKey1).881 Build())882 })883 h1 := sha256.Sum256(testKey1.PubKey().Bytes())884 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {885 op := new(protocol.RemoveKeyOperation)886 op.Entry.KeyHash = h1[:]887 body := new(protocol.UpdateKeyPage)888 body.Operation = append(body.Operation, op)889 send(newTxn("foo/book1/1").890 WithSigner(protocol.AccountUrl("foo", "book1", "1"), 2).891 WithBody(body).892 Initiate(protocol.SignatureTypeLegacyED25519, testKey2).893 Build())894 })895 page := n.GetKeyPage("foo/book1/1")896 require.Len(t, page.Keys, 1)897 //look for the H1 key, which should have been removed898 _, _, found := page.EntryByKeyHash(h1[:])899 require.False(t, found, "key was found in page when it should have been removed")900 //look for the H2 key which was also added before H1 was removed901 _, _, found = page.EntryByKeyHash(h2[:])902 require.True(t, found, "key was not found in page it was expected to be in")903}904func TestSignatorHeight(t *testing.T) {905 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)906 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)907 n := nodes[partitions[1]][0]908 liteKey, fooKey := generateKey(), generateKey()909 liteUrl, err := protocol.LiteTokenAddress(liteKey.PubKey().Bytes(), protocol.ACME, protocol.SignatureTypeED25519)910 require.NoError(t, err)911 tokenUrl := protocol.AccountUrl("foo", "tokens")912 keyBookUrl := protocol.AccountUrl("foo", "book")913 keyPageUrl := protocol.FormatKeyPageUrl(keyBookUrl, 0)914 require.NoError(t, err)915 batch := n.db.Begin(true)916 require.NoError(t, acctesting.CreateLiteTokenAccountWithCredits(batch, liteKey, 1, 1e9))917 require.NoError(t, batch.Commit())918 getHeight := func(u *url.URL) uint64 {919 batch := n.db.Begin(true)920 defer batch.Discard()921 chain, err := batch.Account(u).MainChain().Get()922 require.NoError(t, err)923 return uint64(chain.Height())924 }925 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {926 adi := new(protocol.CreateIdentity)927 adi.Url = protocol.AccountUrl("foo")928 h := sha256.Sum256(fooKey.PubKey().Bytes())929 adi.KeyHash = h[:]930 adi.KeyBookUrl = keyBookUrl931 send(newTxn(liteUrl.RootIdentity().String()).932 WithBody(adi).933 Initiate(protocol.SignatureTypeLegacyED25519, liteKey).934 Build())935 })936 batch = n.db.Begin(true)937 require.NoError(t, acctesting.AddCredits(batch, keyPageUrl, 1e9))938 require.NoError(t, batch.Commit())939 keyPageHeight := getHeight(keyPageUrl)940 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {941 tac := new(protocol.CreateTokenAccount)942 tac.Url = tokenUrl943 tac.TokenUrl = protocol.AcmeUrl()944 send(newTxn("foo").945 WithSigner(protocol.FormatKeyPageUrl(keyBookUrl, 0), 1).946 WithBody(tac).947 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).948 Build())949 })950 require.Equal(t, keyPageHeight, getHeight(keyPageUrl), "Key page height changed")951}952func TestCreateToken(t *testing.T) {953 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)954 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)955 n := nodes[partitions[1]][0]956 fooKey := generateKey()957 batch := n.db.Begin(true)958 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))959 require.NoError(t, batch.Commit())960 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {961 body := new(protocol.CreateToken)962 body.Url = protocol.AccountUrl("foo", "tokens")963 body.Symbol = "FOO"964 body.Precision = 10965 send(newTxn("foo").966 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).967 WithBody(body).968 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).969 Build())970 })971 n.GetTokenIssuer("foo/tokens")972}973func TestIssueTokens(t *testing.T) {974 check := newDefaultCheckError(t, true)975 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)976 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())977 n := nodes[partitions[1]][0]978 fooKey, liteKey := generateKey(), generateKey()979 batch := n.db.Begin(true)980 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))981 require.NoError(t, acctesting.CreateTokenIssuer(batch, "foo/tokens", "FOO", 10, nil))982 require.NoError(t, acctesting.CreateTokenAccount(batch, "foo.acme/acmetokens", "acc://ACME", float64(10), false))983 require.NoError(t, acctesting.CreateLiteTokenAccountWithCredits(batch, liteKey, 1, 1e9))984 liteAddr, err := protocol.LiteTokenAddress(liteKey[32:], "foo.acme/tokens", protocol.SignatureTypeED25519)985 require.NoError(t, err)986 require.NoError(t, batch.Commit())987 // Issue foo.acme/tokens to a foo.acme/tokens lite token account988 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {989 body := new(protocol.IssueTokens)990 body.Recipient = liteAddr991 body.Amount.SetUint64(123)992 send(newTxn("foo/tokens").993 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).994 WithBody(body).995 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).996 Build())997 })998 // Verify tokens were received999 account := n.GetLiteTokenAccount(liteAddr.String())1000 require.Equal(t, "acc://foo.acme/tokens", account.TokenUrl.String())1001 require.Equal(t, int64(123), account.Balance.Int64())1002 // Issue foo.acme/tokens to an ACME token account1003 check.Disable = true1004 initialbalance := n.GetTokenAccount("acc://foo.acme/acmetokens").Balance1005 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1006 body := new(protocol.IssueTokens)1007 body.Recipient = n.GetTokenAccount("acc://foo.acme/acmetokens").Url1008 body.Amount.SetUint64(123)1009 send(newTxn("foo/tokens").1010 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1011 WithBody(body).1012 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1013 Build())1014 })1015 // Verify tokens were not received1016 finalbalance := n.GetTokenAccount("acc://foo.acme/acmetokens").Balance1017 require.Equal(t, initialbalance, finalbalance)1018}1019func TestIssueTokensRefund(t *testing.T) {1020 check := newDefaultCheckError(t, true)1021 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1022 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())1023 n := nodes[partitions[1]][0]1024 fooKey, liteKey := generateKey(), generateKey()1025 sponsorUrl := acctesting.AcmeLiteAddressTmPriv(liteKey).RootIdentity()1026 batch := n.db.Begin(true)1027 fooDecimals := 101028 fooPrecision := uint64(math.Pow(10.0, float64(fooDecimals)))1029 maxSupply := int64(1000000 * fooPrecision)1030 supplyLimit := big.NewInt(maxSupply)1031 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))1032 require.NoError(t, acctesting.CreateLiteIdentity(batch, sponsorUrl.String(), 3))1033 require.NoError(t, acctesting.CreateLiteTokenAccount(batch, tmed25519.PrivKey(liteKey), 1e9))1034 require.NoError(t, batch.Commit())1035 liteAddr, err := protocol.LiteTokenAddress(liteKey[32:], "foo.acme/tokens", protocol.SignatureTypeED25519)1036 require.NoError(t, err)1037 // issue tokens with supply limit1038 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1039 body := new(protocol.CreateToken)1040 body.Url = protocol.AccountUrl("foo", "tokens")1041 body.Symbol = "FOO"1042 body.Precision = uint64(fooDecimals)1043 body.SupplyLimit = supplyLimit1044 send(newTxn("foo").1045 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1046 WithBody(body).1047 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1048 Build())1049 })1050 //test to make sure supply limit is set1051 issuer := n.GetTokenIssuer("foo/tokens")1052 require.Equal(t, supplyLimit.Int64(), issuer.SupplyLimit.Int64())1053 //issue tokens successfully1054 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1055 body := new(protocol.IssueTokens)1056 body.Recipient = liteAddr1057 body.Amount.SetUint64(123)1058 send(newTxn("foo/tokens").1059 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1060 WithBody(body).1061 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1062 Build())1063 })1064 issuer = n.GetTokenIssuer("foo/tokens")1065 require.Equal(t, int64(123), issuer.Issued.Int64())1066 account := n.GetLiteTokenAccount(liteAddr.String())1067 require.Equal(t, "acc://foo.acme/tokens", account.TokenUrl.String())1068 require.Equal(t, int64(123), account.Balance.Int64())1069 //issue tokens to incorrect principal1070 check.Disable = true1071 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1072 body := new(protocol.IssueTokens)1073 liteAddr = liteAddr.WithAuthority(liteAddr.Authority + "u")1074 body.Recipient = liteAddr1075 body.Amount.SetUint64(123)1076 send(newTxn("foo/tokens").1077 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1078 WithBody(body).1079 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1080 Build())1081 })1082 issuer = n.GetTokenIssuer("foo/tokens")1083 require.Equal(t, int64(123), issuer.Issued.Int64())1084}1085type CheckError struct {1086 T *testing.T1087 Disable bool1088 H func(err error)1089}1090func newDefaultCheckError(t *testing.T, enable bool) *CheckError {1091 return &CheckError{T: t, H: NewDefaultErrorHandler(t), Disable: !enable}1092}1093func (c *CheckError) ErrorHandler() func(err error) {1094 return func(err error) {1095 c.T.Helper()1096 if !c.Disable {1097 c.H(err)1098 }1099 }1100}1101func TestIssueTokensWithSupplyLimit(t *testing.T) {1102 check := newDefaultCheckError(t, true)1103 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1104 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())1105 n := nodes[partitions[1]][0]1106 fooKey, liteKey := generateKey(), generateKey()1107 sponsorUrl := acctesting.AcmeLiteAddressTmPriv(liteKey).RootIdentity()1108 batch := n.db.Begin(true)1109 fooDecimals := 101110 fooPrecision := uint64(math.Pow(10.0, float64(fooDecimals)))1111 maxSupply := int64(1000000 * fooPrecision)1112 supplyLimit := big.NewInt(maxSupply)1113 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))1114 require.NoError(t, acctesting.CreateLiteIdentity(batch, sponsorUrl.String(), 3))1115 require.NoError(t, acctesting.CreateLiteTokenAccount(batch, tmed25519.PrivKey(liteKey), 1e9))1116 require.NoError(t, batch.Commit())1117 var err error1118 // issue tokens with supply limit1119 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1120 body := new(protocol.CreateToken)1121 body.Url = protocol.AccountUrl("foo", "tokens")1122 body.Symbol = "FOO"1123 body.Precision = uint64(fooDecimals)1124 body.SupplyLimit = supplyLimit1125 send(newTxn("foo").1126 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1127 WithBody(body).1128 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1129 Build())1130 })1131 //test to make sure supply limit is set1132 issuer := n.GetTokenIssuer("foo/tokens")1133 require.Equal(t, supplyLimit.Int64(), issuer.SupplyLimit.Int64())1134 liteAddr, err := protocol.LiteTokenAddress(liteKey[32:], "foo.acme/tokens", protocol.SignatureTypeED25519)1135 require.NoError(t, err)1136 liteAcmeAddr, err := protocol.LiteTokenAddress(liteKey[32:], protocol.ACME, protocol.SignatureTypeED25519)1137 require.NoError(t, err)1138 liteId := liteAcmeAddr.RootIdentity()1139 underLimit := int64(1000 * fooPrecision)1140 atLimit := int64(maxSupply - underLimit)1141 overLimit := int64(maxSupply + 1)1142 // test under the limit1143 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1144 body := new(protocol.IssueTokens)1145 body.Recipient = liteAddr1146 body.Amount.SetInt64(underLimit)1147 send(newTxn("foo/tokens").1148 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1149 WithBody(body).1150 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1151 Build())1152 })1153 account := n.GetLiteTokenAccount(liteAddr.String())1154 require.Equal(t, underLimit, account.Balance.Int64())1155 issuer = n.GetTokenIssuer("foo/tokens")1156 require.Equal(t, underLimit, issuer.Issued.Int64())1157 //supply limit should not change1158 require.Equal(t, maxSupply, issuer.SupplyLimit.Int64())1159 // test at the limit1160 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1161 body := new(protocol.IssueTokens)1162 body.Recipient = liteAddr1163 body.Amount.SetInt64(atLimit)1164 send(newTxn("foo/tokens").1165 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1166 WithBody(body).1167 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1168 Build())1169 })1170 account = n.GetLiteTokenAccount(liteAddr.String())1171 //the balance should now be at max supply1172 require.Equal(t, maxSupply, account.Balance.Int64())1173 //there should be no more tokens available in the tank1174 issuer = n.GetTokenIssuer("foo/tokens")1175 require.Equal(t, int64(0), issuer.SupplyLimit.Int64()-issuer.Issued.Int64())1176 // test over the limit, this should fail, so tell fake tendermint not to give up1177 // an error will be displayed on the console, but this is exactly what we expect so don't panic1178 check.Disable = true1179 _, _, err = n.Execute(func(send func(*protocol.Envelope)) {1180 body := new(protocol.IssueTokens)1181 body.Recipient = liteAddr1182 body.Amount.SetInt64(overLimit)1183 send(newTxn("foo/tokens").1184 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1185 WithBody(body).1186 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1187 Build())1188 })1189 require.Error(t, err, "expected a failure but instead spending over the supply limit passed")1190 account = n.GetLiteTokenAccount(liteAddr.String())1191 //the balance should be equal to1192 require.Greater(t, overLimit, account.Balance.Int64())1193 //now lets buy some credits, so we can do a token burn1194 check.Disable = false1195 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1196 body := new(protocol.AddCredits)1197 //burn the underLimit amount to see if that gets returned to the pool1198 body.Recipient = liteAddr.RootIdentity()1199 body.Amount.SetUint64(100 * protocol.AcmePrecision)1200 body.Oracle = n.GetOraclePrice()1201 send(newTxn(liteAcmeAddr.String()).1202 WithSigner(liteId.RootIdentity(), 1).1203 WithBody(body).1204 Initiate(protocol.SignatureTypeLegacyED25519, liteKey).1205 Build())1206 })1207 //now lets burn some tokens to see if they get returned to the supply1208 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1209 body := new(protocol.BurnTokens)1210 //burn the underLimit amount to see if that gets returned to the pool1211 body.Amount.SetInt64(underLimit)1212 send(newTxn(liteAddr.String()).1213 WithSigner(liteAddr.RootIdentity(), 1).1214 WithBody(body).1215 Initiate(protocol.SignatureTypeLegacyED25519, liteKey).1216 Build())1217 })1218 account = n.GetLiteTokenAccount(liteAddr.String())1219 // previous balance was maxSupply, so test to make sure underLimit was debited1220 require.Equal(t, maxSupply-underLimit, account.Balance.Int64())1221 //there should now be the maxSupply - underLimit amount as the amount issued now1222 issuer = n.GetTokenIssuer("foo/tokens")1223 require.Equal(t, maxSupply-underLimit, issuer.Issued.Int64())1224}1225func TestInvalidDeposit(t *testing.T) {1226 // The lite address ends with `foo/tokens` but the token is `foo2/tokens` so1227 // the synthetic transaction will fail. This test verifies that the1228 // transaction fails, but more importantly it verifies that1229 // `Executor.Commit()` does *not* break if DeliverTx fails with a1230 // non-existent origin. This is motivated by a bug that has been fixed. This1231 // bug could have been triggered by a failing SyntheticCreateChains,1232 // SyntheticDepositTokens, or SyntheticDepositCredits.1233 t.Skip("TODO Fix - generate a receipt")1234 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1235 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)1236 n := nodes[partitions[1]][0]1237 liteKey := generateKey()1238 liteAddr, err := protocol.LiteTokenAddress(liteKey[32:], "foo/tokens", protocol.SignatureTypeED25519)1239 require.NoError(t, err)1240 id := n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1241 body := new(protocol.SyntheticDepositTokens)1242 body.Cause = n.network.NodeUrl().WithTxID([32]byte{1})1243 body.Token = protocol.AccountUrl("foo2", "tokens")1244 body.Amount.SetUint64(123)1245 send(newTxn(liteAddr.String()).1246 WithBody(body).1247 InitiateSynthetic(n.network.NodeUrl()).1248 Sign(protocol.SignatureTypeLegacyED25519, n.key.Bytes()).1249 Build())1250 })[0]1251 tx := n.GetTx(id[:])1252 require.NotZero(t, tx.Status.Code)1253}1254func DumpAccount(t *testing.T, batch *database.Batch, accountUrl *url.URL) {1255 account := batch.Account(accountUrl)1256 state, err := account.GetState()1257 require.NoError(t, err)1258 fmt.Println("Dump", accountUrl, state.Type())1259 chains, err := account.Chains().Get()1260 require.NoError(t, err)1261 seen := map[[32]byte]bool{}1262 for _, cmeta := range chains {1263 chain, err := account.GetChainByName(cmeta.Name)1264 require.NoError(t, err)1265 fmt.Printf(" Chain: %s (%v)\n", cmeta.Name, cmeta.Type)1266 height := chain.Height()1267 entries, err := chain.Entries(0, height)1268 require.NoError(t, err)1269 for idx, id := range entries {1270 fmt.Printf(" Entry %d: %X\n", idx, id)1271 if cmeta.Type != protocol.ChainTypeTransaction {1272 continue1273 }1274 var id32 [32]byte1275 require.Equal(t, 32, copy(id32[:], id))1276 if seen[id32] {1277 continue1278 }1279 txState, err := batch.Transaction(id).GetState()1280 require.NoError(t, err)1281 txStatus, err := batch.Transaction(id).GetStatus()1282 require.NoError(t, err)1283 if seen[*(*[32]byte)(txState.Transaction.GetHash())] {1284 fmt.Printf(" TX: hash=%X\n", txState.Transaction.GetHash())1285 continue1286 }1287 fmt.Printf(" TX: type=%v origin=%v status=%#v\n", txState.Transaction.Body.Type(), txState.Transaction.Header.Principal, txStatus)1288 seen[id32] = true1289 }1290 }1291}1292func TestMultisig(t *testing.T) {1293 check := newDefaultCheckError(t, true)1294 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1295 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())1296 key1, key2 := acctesting.GenerateTmKey(t.Name(), 1), acctesting.GenerateTmKey(t.Name(), 2)1297 t.Log("Setup")1298 n := nodes[partitions[1]][0]1299 batch := n.db.Begin(true)1300 require.NoError(t, acctesting.CreateADI(batch, key1, "foo"))1301 require.NoError(t, acctesting.UpdateKeyPage(batch, protocol.AccountUrl("foo", "book0", "1"), func(page *protocol.KeyPage) {1302 hash := sha256.Sum256(key2[32:])1303 page.AcceptThreshold = 21304 page.CreditBalance = 1e81305 page.AddKeySpec(&protocol.KeySpec{1306 PublicKeyHash: hash[:],1307 })1308 }))1309 require.NoError(t, batch.Commit())1310 t.Log("Initiate the transaction")1311 ids := n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1312 send(newTxn("foo").1313 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1314 WithBody(&protocol.CreateTokenAccount{1315 Url: protocol.AccountUrl("foo", "tokens"),1316 TokenUrl: protocol.AcmeUrl(),1317 }).1318 Initiate(protocol.SignatureTypeED25519, key1.Bytes()).1319 Build())1320 })1321 txnResp := n.QueryTransaction(fmt.Sprintf("foo?txid=%X", ids[0]))1322 require.False(t, txnResp.Status.Delivered(), "Transaction is was delivered")1323 require.True(t, txnResp.Status.Pending(), "Transaction is not pending")1324 t.Log("Double signing with key 1 should not complete the transaction")1325 sigHashes, _ := n.MustExecute(func(send func(*protocol.Envelope)) {1326 send(acctesting.NewTransaction().1327 WithTimestampVar(&globalNonce).1328 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1329 WithTxnHash(ids[0][:]).1330 Sign(protocol.SignatureTypeED25519, key1.Bytes()).1331 Build())1332 })1333 n.MustWaitForTxns(convertIds32(sigHashes...)...)1334 txnResp = n.QueryTransaction(fmt.Sprintf("foo?txid=%X", ids[0]))1335 require.False(t, txnResp.Status.Delivered(), "Transaction is was delivered")1336 require.True(t, txnResp.Status.Pending(), "Transaction is not pending")1337 t.Log("Signing with key 2 should complete the transaction")1338 sigHashes, _ = n.MustExecute(func(send func(*protocol.Envelope)) {1339 send(acctesting.NewTransaction().1340 WithTimestampVar(&globalNonce).1341 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1342 WithTxnHash(ids[0][:]).1343 Sign(protocol.SignatureTypeED25519, key2.Bytes()).1344 Build())1345 })1346 n.MustWaitForTxns(convertIds32(sigHashes...)...)1347 txnResp = n.QueryTransaction(fmt.Sprintf("foo?txid=%X", ids[0]))1348 require.True(t, txnResp.Status.Delivered(), "Transaction is was not delivered")1349 require.False(t, txnResp.Status.Pending(), "Transaction is still pending")1350 // this should fail, so tell fake tendermint not to give up1351 // an error will be displayed on the console, but this is exactly what we expect so don't panic1352 check.Disable = true1353 t.Run("Signing a complete transaction should fail", func(t *testing.T) {1354 t.Skip("No longer an error")1355 _, _, err := n.Execute(func(send func(*protocol.Envelope)) {1356 send(acctesting.NewTransaction().1357 WithTimestampVar(&globalNonce).1358 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1359 WithTxnHash(ids[0][:]).1360 Sign(protocol.SignatureTypeED25519, key2.Bytes()).1361 Build())1362 })1363 require.Error(t, err)1364 })1365}1366func TestAccountAuth(t *testing.T) {1367 check := newDefaultCheckError(t, true)1368 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1369 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())1370 n := nodes[partitions[1]][0]1371 fooKey, barKey := generateKey(), generateKey()1372 batch := n.db.Begin(true)1373 require.NoError(t, acctesting.CreateAdiWithCredits(batch, fooKey, "foo", 1e9))1374 require.NoError(t, acctesting.CreateTokenAccount(batch, "foo/tokens", protocol.AcmeUrl().String(), 1, false))1375 require.NoError(t, acctesting.CreateSubADI(batch, "foo", "foo/bar"))1376 require.NoError(t, acctesting.CreateTokenAccount(batch, "foo/bar/tokens", protocol.AcmeUrl().String(), 0, false))1377 require.NoError(t, acctesting.CreateKeyBook(batch, "foo/bar/book", barKey.PubKey().Bytes()))1378 require.NoError(t, acctesting.AddCredits(batch, protocol.AccountUrl("foo", "bar", "book", "1"), 1e9))1379 require.NoError(t, batch.Commit())1380 // Disable auth1381 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1382 send(newTxn("foo/tokens").1383 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1384 WithBody(&protocol.UpdateAccountAuth{1385 Operations: []protocol.AccountAuthOperation{1386 &protocol.DisableAccountAuthOperation{1387 Authority: protocol.AccountUrl("foo", "book0"),1388 },1389 },1390 }).1391 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1392 Build())1393 })1394 // An unauthorized signer must not be allowed to enable auth1395 check.Disable = true1396 _, _, err := n.Execute(func(send func(*protocol.Envelope)) {1397 send(newTxn("foo/tokens").1398 WithSigner(protocol.AccountUrl("foo", "bar", "book", "1"), 1).1399 WithBody(&protocol.UpdateAccountAuth{1400 Operations: []protocol.AccountAuthOperation{1401 &protocol.EnableAccountAuthOperation{1402 Authority: protocol.AccountUrl("foo", "book0"),1403 },1404 },1405 }).1406 Initiate(protocol.SignatureTypeLegacyED25519, barKey).1407 Build())1408 })1409 require.Error(t, err, "An unauthorized signer should not be able to enable auth")1410 // An unauthorized signer should be able to send tokens1411 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1412 exch := new(protocol.SendTokens)1413 exch.AddRecipient(protocol.AccountUrl("foo", "bar", "tokens"), big.NewInt(int64(68)))1414 send(newTxn("foo/tokens").1415 WithSigner(protocol.AccountUrl("foo", "bar", "book", "1"), 1).1416 WithBody(exch).1417 Initiate(protocol.SignatureTypeLegacyED25519, barKey).1418 Build())1419 })1420 require.Equal(t, int64(protocol.AcmePrecision-68), n.GetTokenAccount("foo/tokens").Balance.Int64())1421 require.Equal(t, int64(68), n.GetTokenAccount("foo/bar/tokens").Balance.Int64())1422 // Enable auth1423 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1424 send(newTxn("foo/tokens").1425 WithSigner(protocol.AccountUrl("foo", "book0", "1"), 1).1426 WithBody(&protocol.UpdateAccountAuth{1427 Operations: []protocol.AccountAuthOperation{1428 &protocol.EnableAccountAuthOperation{1429 Authority: protocol.AccountUrl("foo", "book0"),1430 },1431 },1432 }).1433 Initiate(protocol.SignatureTypeLegacyED25519, fooKey).1434 Build())1435 })1436 // An unauthorized signer should no longer be able to send tokens1437 check.Disable = true1438 _, _, err = n.Execute(func(send func(*protocol.Envelope)) {1439 exch := new(protocol.SendTokens)1440 exch.AddRecipient(protocol.AccountUrl("foo", "bar", "tokens"), big.NewInt(int64(68)))1441 send(newTxn("foo/tokens").1442 WithSigner(protocol.AccountUrl("foo", "bar", "book", "1"), 1).1443 WithBody(exch).1444 Initiate(protocol.SignatureTypeLegacyED25519, barKey).1445 Build())1446 })1447 require.Error(t, err, "expected a failure but instead an unauthorized signature succeeded")1448}1449func TestDelegatedKeypageUpdate(t *testing.T) {1450 check := newDefaultCheckError(t, false)1451 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1452 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())1453 n := nodes[partitions[1]][0]1454 aliceKey, charlieKey, bobKey, jjkey, newKey1, newKey2 := generateKey(), generateKey(), generateKey(), generateKey(), generateKey(), generateKey()1455 charliekeyHash := sha256.Sum256(charlieKey.PubKey().Address())1456 newKey1hash := sha256.Sum256(newKey1.PubKey().Address())1457 newKey2hash := sha256.Sum256(newKey2.PubKey().Address())1458 batch := n.db.Begin(true)1459 require.NoError(t, acctesting.CreateAdiWithCredits(batch, aliceKey, "alice", 1e9))1460 require.NoError(t, acctesting.CreateAdiWithCredits(batch, bobKey, "bob", 1e9))1461 require.NoError(t, acctesting.CreateAdiWithCredits(batch, charlieKey, "charlie", 1e9))1462 require.NoError(t, acctesting.CreateAdiWithCredits(batch, jjkey, "jj", 1e9))1463 require.NoError(t, acctesting.UpdateKeyPage(batch, protocol.AccountUrl("alice", "book0", "1"), func(kp *protocol.KeyPage) {1464 kp.AddKeySpec(&protocol.KeySpec{Delegate: protocol.AccountUrl("bob", "book0")})1465 kp.AddKeySpec(&protocol.KeySpec{Delegate: protocol.AccountUrl("charlie", "book0")})1466 kp.AddKeySpec(&protocol.KeySpec{PublicKeyHash: charliekeyHash[:]})1467 }))1468 require.NoError(t, acctesting.UpdateKeyPage(batch, protocol.AccountUrl("bob", "book0", "1"), func(kp *protocol.KeyPage) {1469 kp.AddKeySpec(&protocol.KeySpec{Delegate: protocol.AccountUrl("charlie", "book0")})1470 }))1471 require.NoError(t, batch.Commit())1472 page := n.GetKeyPage("jj/book0/1")1473 //look for the key.1474 _, _, found := page.EntryByKeyHash(newKey1hash[:])1475 require.False(t, found, "key not found in page")1476 //Test with single level Key1477 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1478 body := new(protocol.UpdateKey)1479 body.NewKeyHash = newKey1hash[:]1480 send(newTxn("jj/book0/1").WithSigner(protocol.AccountUrl("jj", "book0", "1"), 1).WithBody(body).1481 Initiate(protocol.SignatureTypeLegacyED25519, jjkey).1482 Build())1483 })1484 page = n.GetKeyPage("jj/book0/1")1485 //look for the key.1486 _, _, found = page.EntryByKeyHash(newKey1hash[:])1487 require.True(t, found, "key not found in page")1488 page = n.GetKeyPage("alice/book0/1")1489 //look for the key.1490 _, _, found = page.EntryByKeyHash(newKey2hash[:])1491 require.False(t, found, "key not found in page")1492 //Test with singleLevel Delegation1493 n.MustExecuteAndWait(func(send func(*protocol.Envelope)) {1494 body := new(protocol.UpdateKey)1495 body.NewKeyHash = newKey2hash[:]1496 send(newTxn("alice/book0/1").1497 WithBody(body).1498 // Sign with Charlie via Alice (one-layer delegation)1499 WithSigner(protocol.AccountUrl("charlie", "book0", "1"), 1).1500 WithDelegator(protocol.AccountUrl("alice", "book0", "1")).1501 Initiate(protocol.SignatureTypeED25519, charlieKey).1502 Build())1503 })1504 page = n.GetKeyPage("alice/book0/1")1505 //look for the key.1506 _, _, found = page.EntryByKeyHash(newKey2hash[:])1507 require.True(t, found, "key not found in page")1508}1509func TestMultiLevelDelegation(t *testing.T) {1510 check := newDefaultCheckError(t, false)1511 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1512 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())1513 n := nodes[partitions[1]][0]1514 aliceKey, charlieKey, bobKey := generateKey(), generateKey(), generateKey()1515 charliekeyHash := sha256.Sum256(charlieKey.PubKey().Address())1516 batch := n.db.Begin(true)1517 require.NoError(t, acctesting.CreateAdiWithCredits(batch, aliceKey, "alice", 1e9))1518 require.NoError(t, acctesting.CreateAdiWithCredits(batch, bobKey, "bob", 1e9))1519 require.NoError(t, acctesting.CreateAdiWithCredits(batch, charlieKey, "charlie", 1e9))1520 require.NoError(t, acctesting.UpdateKeyPage(batch, protocol.AccountUrl("alice", "book0", "1"), func(kp *protocol.KeyPage) {1521 kp.AddKeySpec(&protocol.KeySpec{Delegate: protocol.AccountUrl("bob", "book0")})1522 kp.AddKeySpec(&protocol.KeySpec{Delegate: protocol.AccountUrl("charlie", "book0")})1523 kp.AddKeySpec(&protocol.KeySpec{PublicKeyHash: charliekeyHash[:]})1524 require.NoError(t, kp.SetThreshold(3))1525 }))1526 require.NoError(t, acctesting.UpdateKeyPage(batch, protocol.AccountUrl("bob", "book0", "1"), func(kp *protocol.KeyPage) {1527 kp.AddKeySpec(&protocol.KeySpec{Delegate: protocol.AccountUrl("charlie", "book0")})1528 }))1529 require.NoError(t, batch.Commit())1530 _, _, err := n.Execute(func(send func(*protocol.Envelope)) {1531 cda := new(protocol.CreateDataAccount)1532 cda.Url = protocol.AccountUrl("alice", "data")1533 env := newTxn("alice").1534 WithBody(cda).1535 // Initiate with Alice1536 WithSigner(protocol.AccountUrl("alice", "book0", "1"), 1).1537 Initiate(protocol.SignatureTypeED25519, aliceKey).1538 // Sign with Charlie via Alice (one-layer delegation)1539 WithSigner(protocol.AccountUrl("charlie", "book0", "1"), 1).1540 WithDelegator(protocol.AccountUrl("alice", "book0", "1")).1541 Sign(protocol.SignatureTypeED25519, charlieKey).1542 Build()1543 // Take Charlie's signature, extract the key signature, and reconstruct1544 // it as via Bob via Alice (two-layer delegation)1545 sig := env.Signatures[1].(*protocol.DelegatedSignature).Signature1546 sig = &protocol.DelegatedSignature{Delegator: protocol.AccountUrl("bob", "book0", "1"), Signature: sig}1547 sig = &protocol.DelegatedSignature{Delegator: protocol.AccountUrl("alice", "book0", "1"), Signature: sig}1548 env.Signatures = append(env.Signatures, sig)1549 send(env)1550 })1551 require.Error(t, err)1552 var resp *abci.ResponseCheckTx1553 require.NoError(t, json.Unmarshal([]byte(err.Error()), &resp), "Expected error to be a CheckTx response")1554 result := new(protocol.TransactionResultSet)1555 require.NoError(t, result.UnmarshalBinary(resp.Data))1556 require.Len(t, result.Results, 1)1557 require.NotNil(t, result.Results[0].Error)1558 require.EqualError(t, result.Results[0].Error, "signature 2: invalid signature")1559}1560func TestDuplicateKeyNewKeypage(t *testing.T) {1561 check := newDefaultCheckError(t, false)1562 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1563 nodes := RunTestNet(t, partitions, daemons, nil, true, check.ErrorHandler())1564 n := nodes[partitions[1]][0]1565 aliceKey := generateKey()1566 aliceKeyHash := sha256.Sum256(aliceKey.PubKey().Bytes())1567 aliceKey1 := generateKey()1568 aliceKeyHash1 := sha256.Sum256(aliceKey1.PubKey().Bytes())1569 batch := n.db.Begin(true)1570 require.NoError(t, acctesting.CreateAdiWithCredits(batch, aliceKey, "alice", 1e9))1571 require.NoError(t, batch.Commit())1572 page := n.GetKeyPage("alice/book0/1")1573 require.Len(t, page.Keys, 1)1574 key := page.Keys[0]1575 require.Equal(t, uint64(0), key.LastUsedOn)1576 require.Equal(t, aliceKeyHash[:], key.PublicKeyHash)1577 //check for unique keys1578 _, txns, err := n.Execute(func(send func(*protocol.Envelope)) {1579 cms := new(protocol.CreateKeyPage)1580 cms.Keys = append(cms.Keys, &protocol.KeySpecParams{1581 KeyHash: aliceKeyHash[:],1582 })1583 cms.Keys = append(cms.Keys, &protocol.KeySpecParams{1584 KeyHash: aliceKeyHash1[:],1585 })1586 send(newTxn("alice/book0").1587 WithSigner(protocol.AccountUrl("alice", "book0", "1"), 1).1588 WithBody(cms).1589 Initiate(protocol.SignatureTypeLegacyED25519, aliceKey).1590 Build())1591 })1592 require.NoError(t, err)1593 n.MustWaitForTxns(txns[0][:])1594 page = n.GetKeyPage("alice/book0/2")1595 require.Len(t, page.Keys, 2)1596 _, key1, alice1Found := page.EntryByKeyHash(aliceKeyHash[:])1597 _, key2, alice2Found := page.EntryByKeyHash(aliceKeyHash1[:])1598 require.True(t, alice1Found, "alice key 1 not found")1599 require.Equal(t, uint64(0), key1.GetLastUsedOn())1600 require.True(t, alice2Found, "alice key 2 not found")1601 require.Equal(t, uint64(0), key2.GetLastUsedOn())1602 //check for duplicate keys1603 _, _, err = n.Execute(func(send func(*protocol.Envelope)) {1604 cms := new(protocol.CreateKeyPage)1605 cms.Keys = append(cms.Keys, &protocol.KeySpecParams{1606 KeyHash: aliceKeyHash[:],1607 })1608 cms.Keys = append(cms.Keys, &protocol.KeySpecParams{1609 KeyHash: aliceKeyHash[:],1610 })1611 send(newTxn("alice/book0").1612 WithSigner(protocol.AccountUrl("alice", "book0", "1"), 1).1613 WithBody(cms).1614 Initiate(protocol.SignatureTypeLegacyED25519, aliceKey).1615 Build())1616 })1617 var resp *abci.ResponseCheckTx1618 require.NoError(t, json.Unmarshal([]byte(err.Error()), &resp), "Expected error to be a CheckTx response")1619 result := new(protocol.TransactionResultSet)1620 require.NoError(t, result.UnmarshalBinary(resp.Data))1621 require.Len(t, result.Results, 1)1622 require.NotNil(t, result.Results[0].Error)1623 require.EqualError(t, result.Results[0].Error, "duplicate keys: signing keys of a keypage must be unique")1624}1625func TestNetworkDefinition(t *testing.T) {1626 partitions, daemons := acctesting.CreateTestNet(t, 1, 1, 0, false)1627 nodes := RunTestNet(t, partitions, daemons, nil, true, nil)...

Full Screen

Full Screen

state_test.go

Source:state_test.go Github

copy

Full Screen

...47 acctesting.NewTransaction().48 WithPrincipal(name.JoinPath("tokens")).49 WithSigner(name.JoinPath("book", "1"), 1).50 WithTimestampVar(&timestamp).51 WithBody(&SendTokens{52 To: []*TokenRecipient{53 {Url: liteUrl, Amount: *big.NewInt(68)},54 },55 }).56 Initiate(SignatureTypeED25519, key).57 Build(),58 )...)59}60func SetupIdentity(sim *simulator.Simulator, name *url.URL, key []byte, timestamp *uint64) {61 // Fund a lite account62 liteKey := acctesting.GenerateKey(sim.Name(), "SetupIdentity", name)63 liteUrl := acctesting.AcmeLiteAddressStdPriv(liteKey)64 sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(65 acctesting.NewTransaction().66 WithPrincipal(FaucetUrl).67 WithBody(&AcmeFaucet{Url: liteUrl}).68 Faucet(),69 )...)70 // Add credits to the lite account71 const liteCreditAmount = 1 * AcmePrecision72 sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(73 acctesting.NewTransaction().74 WithPrincipal(liteUrl).75 WithSigner(liteUrl, 1).76 WithTimestampVar(timestamp).77 WithBody(&AddCredits{78 Recipient: liteUrl,79 Amount: *big.NewInt(liteCreditAmount),80 Oracle: InitialAcmeOracleValue,81 }).82 Initiate(SignatureTypeED25519, liteKey).83 Build(),84 )...)85 // Create the ADI86 sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(87 acctesting.NewTransaction().88 WithPrincipal(liteUrl).89 WithSigner(liteUrl, 1).90 WithTimestampVar(timestamp).91 WithBody(&CreateIdentity{92 Url: name,93 KeyBookUrl: name.JoinPath("book"),94 KeyHash: doSha256(key[32:]),95 }).96 Initiate(SignatureTypeED25519, liteKey).97 Build(),98 )...)99 // Add credits to the key page100 const tokenAccountAmount = 5 * AcmePrecision101 sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(102 acctesting.NewTransaction().103 WithPrincipal(liteUrl).104 WithSigner(liteUrl, 1).105 WithTimestampVar(timestamp).106 WithBody(&AddCredits{107 Recipient: name.JoinPath("book", "1"),108 Amount: *big.NewInt(AcmePrecision*AcmeFaucetAmount - liteCreditAmount - tokenAccountAmount),109 Oracle: InitialAcmeOracleValue,110 }).111 Initiate(SignatureTypeED25519, liteKey).112 Build(),113 )...)114 // Create a token account115 sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(116 acctesting.NewTransaction().117 WithPrincipal(name).118 WithSigner(name.JoinPath("book", "1"), 1).119 WithTimestampVar(timestamp).120 WithBody(&CreateTokenAccount{121 Url: name.JoinPath("tokens"),122 TokenUrl: AcmeUrl(),123 }).124 Initiate(SignatureTypeED25519, key).125 Build(),126 )...)127 // Send tokens to the ADI token account128 sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(129 acctesting.NewTransaction().130 WithPrincipal(liteUrl).131 WithSigner(liteUrl, 1).132 WithTimestampVar(timestamp).133 WithBody(&SendTokens{134 To: []*TokenRecipient{135 {Url: name.JoinPath("tokens"), Amount: *big.NewInt(tokenAccountAmount)},136 },137 }).138 Initiate(SignatureTypeED25519, liteKey).139 Build(),140 )...)141}...

Full Screen

Full Screen

txn_lock_account_test.go

Source:txn_lock_account_test.go Github

copy

Full Screen

...23 acctesting.NewTransaction().24 WithPrincipal(lite).25 WithSigner(lite, 1).26 WithTimestampVar(&timestamp).27 WithBody(&SendTokens{To: []*TokenRecipient{{Url: recipient, Amount: *big.NewInt(1)}}}).28 Initiate(SignatureTypeED25519, liteKey).29 Build(),30 )...)31 require.False(t, st[0].Failed(), "Expected the transaction to succeed")32 require.Equal(t, int(1), int(simulator.GetAccount[*LiteTokenAccount](sim, recipient).Balance.Int64()))33 // Lock34 st, _ = sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(35 acctesting.NewTransaction().36 WithPrincipal(lite).37 WithSigner(lite, 1).38 WithTimestampVar(&timestamp).39 WithBody(&LockAccount{Height: 10}).40 Initiate(SignatureTypeED25519, liteKey).41 Build(),42 )...)43 require.False(t, st[0].Failed(), "Expected the transaction to succeed")44 require.Equal(t, int(10), int(simulator.GetAccount[*LiteTokenAccount](sim, lite).LockHeight))45 // Locked, cannot send46 _, err := sim.SubmitAndExecuteBlock(47 acctesting.NewTransaction().48 WithPrincipal(lite).49 WithSigner(lite, 1).50 WithTimestampVar(&timestamp).51 WithBody(&SendTokens{To: []*TokenRecipient{{Url: recipient, Amount: *big.NewInt(1)}}}).52 Initiate(SignatureTypeED25519, liteKey).53 Build(),54 )55 require.Error(t, err)56 // Fake a major block57 x := sim.PartitionFor(lite)58 _ = x.Database.Update(func(batch *database.Batch) error {59 entry, err := (&IndexEntry{BlockIndex: 10}).MarshalBinary()60 require.NoError(t, err)61 chain, err := batch.Account(x.Executor.Describe.AnchorPool()).MajorBlockChain().Get()62 require.NoError(t, err)63 require.NoError(t, chain.AddEntry(entry, false))64 return nil65 })66 // Lock expired, can send67 st, _ = sim.WaitForTransactions(delivered, sim.MustSubmitAndExecuteBlock(68 acctesting.NewTransaction().69 WithPrincipal(lite).70 WithSigner(lite, 1).71 WithTimestampVar(&timestamp).72 WithBody(&SendTokens{To: []*TokenRecipient{{Url: recipient, Amount: *big.NewInt(1)}}}).73 Initiate(SignatureTypeED25519, liteKey).74 Build(),75 )...)76 require.False(t, st[0].Failed(), "Expected the transaction to succeed")77 require.Equal(t, int(2), int(simulator.GetAccount[*LiteTokenAccount](sim, recipient).Balance.Int64()))78}79func TestLockAccount_LiteToken_WrongSigner(t *testing.T) {80 liteKey := acctesting.GenerateKey("Lite")81 lite := acctesting.AcmeLiteAddressStdPriv(liteKey)82 alice := AccountUrl("alice")83 aliceKey := acctesting.GenerateKey(alice)84 // Initialize85 var timestamp uint6486 sim := simulator.New(t, 3)87 sim.InitFromGenesis()88 sim.CreateAccount(&LiteIdentity{Url: lite.RootIdentity(), CreditBalance: 1e9})89 sim.CreateAccount(&LiteTokenAccount{Url: lite, TokenUrl: AcmeUrl(), Balance: *big.NewInt(10)})90 sim.CreateIdentity(alice, aliceKey[32:])91 updateAccount(sim, alice.JoinPath("book", "1"), func(p *KeyPage) { p.CreditBalance = 1e9 })92 // Attempt to lock93 envs := sim.MustSubmitAndExecuteBlock(94 acctesting.NewTransaction().95 WithPrincipal(lite).96 WithSigner(alice.JoinPath("book", "1"), 1).97 WithTimestampVar(&timestamp).98 WithBody(&LockAccount{Height: 10}).99 Initiate(SignatureTypeED25519, aliceKey).100 Build(),101 )102 sim.WaitForTransaction(delivered, envs[0].Transaction[0].GetHash(), 50) // TODO How do we wait for the signature?103 // Verify nothing changed104 require.Zero(t, int(simulator.GetAccount[*LiteTokenAccount](sim, lite).LockHeight))105}...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful