The core protocol of WoopChain
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
woop/test/chain/main.go

238 lines
9.3 KiB

package main
import (
"crypto/ecdsa"
"fmt"
"log"
"math/big"
"github.com/ethereum/go-ethereum/core/rawdb"
chain2 "github.com/harmony-one/harmony/test/chain/chain"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
blockfactory "github.com/harmony-one/harmony/block/factory"
"github.com/harmony-one/harmony/core"
core_state "github.com/harmony-one/harmony/core/state"
3 years ago
harmonyState "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/core/vm"
"github.com/harmony-one/harmony/crypto/hash"
"github.com/harmony-one/harmony/internal/params"
pkgworker "github.com/harmony-one/harmony/node/worker"
)
const (
// FaucetContractBinary is binary for faucet contract.
FaucetContractBinary = "0x60806040526706f05b59d3b2000060015560028054600160a060020a031916331790556101aa806100316000396000f3fe608060405260043610610045577c0100000000000000000000000000000000000000000000000000000000600035046327c78c42811461004a578063b69ef8a81461008c575b600080fd5b34801561005657600080fd5b5061008a6004803603602081101561006d57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166100b3565b005b34801561009857600080fd5b506100a1610179565b60408051918252519081900360200190f35b60025473ffffffffffffffffffffffffffffffffffffffff1633146100d757600080fd5b600154303110156100e757600080fd5b73ffffffffffffffffffffffffffffffffffffffff811660009081526020819052604090205460ff161561011a57600080fd5b73ffffffffffffffffffffffffffffffffffffffff8116600081815260208190526040808220805460ff1916600190811790915554905181156108fc0292818181858888f19350505050158015610175573d6000803e3d6000fd5b5050565b30319056fea165627a7a723058206b894c1f3badf3b26a7a2768ab8141b1e6fa1c1ddc4622f4f44a7d5041edc9350029"
)
var (
//FaucetPriKey for the faucet contract Test accounts
FaucetPriKey, _ = crypto.GenerateKey()
//FaucetAddress generated via the key.
FaucetAddress = crypto.PubkeyToAddress(FaucetPriKey.PublicKey)
//FaucetInitFunds initial funds in facuet contract
FaucetInitFunds = big.NewInt(8000000000000000000)
testUserKey, _ = crypto.GenerateKey()
testUserAddress = crypto.PubkeyToAddress(testUserKey.PublicKey)
chainConfig = params.TestChainConfig
blockFactory = blockfactory.ForTest
// Test transactions
pendingTxs []types.PoolTransaction
database = rawdb.NewMemoryDatabase()
gspec = core.Genesis{
Config: chainConfig,
Factory: blockFactory,
Alloc: core.GenesisAlloc{FaucetAddress: {Balance: FaucetInitFunds}},
ShardID: 0,
}
txs []*types.Transaction
contractworker *pkgworker.Worker
nonce uint64
dataEnc []byte
allRandomUserAddress []common.Address
allRandomUserKey []*ecdsa.PrivateKey
faucetContractAddress common.Address
chain core.BlockChain
err error
state *core_state.DB
)
func init() {
firstRandomUserKey, _ := crypto.GenerateKey()
firstRandomUserAddress := crypto.PubkeyToAddress(firstRandomUserKey.PublicKey)
secondRandomUserKey, _ := crypto.GenerateKey()
secondRandomUserAddress := crypto.PubkeyToAddress(secondRandomUserKey.PublicKey)
thirdRandomUserKey, _ := crypto.GenerateKey()
thirdRandomUserAddress := crypto.PubkeyToAddress(thirdRandomUserKey.PublicKey)
//Transactions by first, second and third user with different staking amounts.
tx1, _ := types.SignTx(types.NewTransaction(0, firstRandomUserAddress, 0, big.NewInt(10), params.TxGas, nil, nil), types.HomesteadSigner{}, FaucetPriKey)
tx2, _ := types.SignTx(types.NewTransaction(1, secondRandomUserAddress, 0, big.NewInt(20), params.TxGas, nil, nil), types.HomesteadSigner{}, FaucetPriKey)
tx3, _ := types.SignTx(types.NewTransaction(2, thirdRandomUserAddress, 0, big.NewInt(30), params.TxGas, nil, nil), types.HomesteadSigner{}, FaucetPriKey)
pendingTxs = append(pendingTxs, tx1)
pendingTxs = append(pendingTxs, tx2)
pendingTxs = append(pendingTxs, tx3)
//tx4, _ := types.SignTx(types.NewTransaction(1, testUserAddress, 0, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, FaucetPriKey)
//newTxs = append(newTxs, tx4)
}
type testWorkerBackend struct {
db ethdb.Database
txPool *core.TxPool
chain *core.BlockChainImpl
}
func fundFaucetContract(chain core.BlockChain) {
fmt.Println()
fmt.Println("--------- Funding addresses for Faucet Contract Call ---------")
fmt.Println()
contractworker = pkgworker.New(params.TestChainConfig, chain, chain.Engine())
nonce = contractworker.GetCurrentState().GetNonce(crypto.PubkeyToAddress(FaucetPriKey.PublicKey))
dataEnc = common.FromHex(FaucetContractBinary)
ftx, _ := types.SignTx(
types.NewContractCreation(
nonce, 0, big.NewInt(7000000000000000000),
params.TxGasContractCreation*10, nil, dataEnc),
types.HomesteadSigner{}, FaucetPriKey,
)
faucetContractAddress = crypto.CreateAddress(FaucetAddress, nonce)
txs = append(txs, ftx)
// Funding the user addressed
for i := 1; i <= 3; i++ {
randomUserKey, _ := crypto.GenerateKey()
randomUserAddress := crypto.PubkeyToAddress(randomUserKey.PublicKey)
amount := i*100000 + 37 // Put different amount in each account.
tx, _ := types.SignTx(types.NewTransaction(nonce+uint64(i), randomUserAddress, 0, big.NewInt(int64(amount)), params.TxGas, nil, nil), types.HomesteadSigner{}, FaucetPriKey)
allRandomUserAddress = append(allRandomUserAddress, randomUserAddress)
allRandomUserKey = append(allRandomUserKey, randomUserKey)
txs = append(txs, tx)
}
amount := 720000
randomUserKey, _ := crypto.GenerateKey()
randomUserAddress := crypto.PubkeyToAddress(randomUserKey.PublicKey)
tx, _ := types.SignTx(types.NewTransaction(nonce+uint64(4), randomUserAddress, 0, big.NewInt(int64(amount)), params.TxGas, nil, nil), types.HomesteadSigner{}, FaucetPriKey)
txs = append(txs, tx)
txmap := make(map[common.Address]types.Transactions)
txmap[FaucetAddress] = txs
err := contractworker.CommitTransactions(
txmap, nil, testUserAddress,
)
if err != nil {
fmt.Println(err)
}
commitSigs := make(chan []byte)
go func() {
commitSigs <- []byte{}
}()
[slash][consensus] Notice double sign & broadcast, factor out tech debt of consensus (#2152) * [slash] Remove dead interface, associated piping * [slash] Expand out structs * [consensus] Write to a chan when find a case of double-signing, remove dead code * [slash] Broadcast the noticing of a double signing * [rawdb] CRUD for slashing candidates * [slashing][node][proto] Broadcast the slash record after receive from consensus, handle received proto message, persist in off-chain db while pending * [slash][node][propose-block] Add verified slashes proposed into the header in block proposal * [slash][shard] Factor out external validator as method on shard state, add double-signature field * [slash][engine] Apply slash, name boolean expression for sorts, use stable sort * [slash] Abstract Ballot results so keep track of both pre and post double sign event * [slash] Fix type errors on test code * [slash] Read from correct rawdb * [slash] Add epoch based guards in CRUD of slashing * [slash] Write to correct cache for slashing candidates * [shard] Use explicit named type of BLS Signature, use convention * [slash] Fix mistake done in refactor, improper header used. Factor out fromSlice to set * [slash][node] Restore newblock to master, try again minimial change * [cx-receipts] Break up one-liner, use SliceStable, not Slice * [network] Finish refactor that makes network message headers once * [network] Simplify creation further of headers write * [slash] Adjust data structure of slash after offline discussion with RJ, Chao * [slash] Still did need signature of the double signature * [consensus] Prepare message does not have block header * [consensus] Soft reset three files to 968517d~1 * [consensus] Begin factor consensus network intended message out with prepare first * [consensus] Factor out Prepared message * [consensus] Factor out announce message creation * [consensus] Committed Message, branch on verify sender key for clearer log * [consensus] Committed Message Factor out * [consensus] Do jenkins MVP of signatures adjustment * [main][slash] Provide YAML config as webhook config for double sign event * [consensus] Adjust signatures, whitespace, lessen GC pressure * [consensus] Remove dead code * [consensus] Factor out commit overloaded message, give commit payload override in construct * [consensus] Fix travis tests * [consensus] Provide block bytes in SubmitVote(quorum.Commit) * [consensus] Factor out noisy sanity checks in BFT, move existing commit check earlier as was before * [quorum] Adjust signatures in quorum * [staking] Adjust after merge from master * [consensus] Finish refactor of consensus * [node] Fix import * [consensus] Fix travis * [consensus] Use origin/master copy of block, fix mistake of pointer to empty byte * [consensus] Less verbose bools * [consensus] Remove unused trailing mutation hook in message construct * [consensus] Address some TODOs on err, comment out double sign
5 years ago
block, _ := contractworker.
FinalizeNewBlock(commitSigs, func() uint64 { return 0 }, common.Address{}, nil, nil)
_, err = chain.InsertChain(types.Blocks{block}, true /* verifyHeaders */)
if err != nil {
fmt.Println(err)
}
state = contractworker.GetCurrentState()
fmt.Println("Balances before call of faucet contract")
fmt.Println("contract balance:")
fmt.Println(state.GetBalance(faucetContractAddress))
fmt.Println("user address balance")
fmt.Println(state.GetBalance(allRandomUserAddress[0]))
fmt.Println()
fmt.Println("--------- Funding addresses for Faucet Contract Call DONE ---------")
}
func callFaucetContractToFundAnAddress(chain core.BlockChain) {
// Send Faucet Contract Transaction ///
fmt.Println("--------- Now Setting up Faucet Contract Call ---------")
fmt.Println()
paddedAddress := common.LeftPadBytes(allRandomUserAddress[0].Bytes(), 32)
transferFnSignature := []byte("request(address)")
fnHash := hash.Keccak256(transferFnSignature)
callFuncHex := fnHash[:4]
var callEnc []byte
callEnc = append(callEnc, callFuncHex...)
callEnc = append(callEnc, paddedAddress...)
callfaucettx, _ := types.SignTx(types.NewTransaction(nonce+uint64(5), faucetContractAddress, 0, big.NewInt(0), params.TxGasContractCreation*10, nil, callEnc), types.HomesteadSigner{}, FaucetPriKey)
txmap := make(map[common.Address]types.Transactions)
txmap[FaucetAddress] = types.Transactions{callfaucettx}
err = contractworker.CommitTransactions(
txmap, nil, testUserAddress,
)
if err != nil {
fmt.Println(err)
}
if err != nil {
fmt.Println(err)
}
commitSigs := make(chan []byte)
go func() {
commitSigs <- []byte{}
}()
[slash][consensus] Notice double sign & broadcast, factor out tech debt of consensus (#2152) * [slash] Remove dead interface, associated piping * [slash] Expand out structs * [consensus] Write to a chan when find a case of double-signing, remove dead code * [slash] Broadcast the noticing of a double signing * [rawdb] CRUD for slashing candidates * [slashing][node][proto] Broadcast the slash record after receive from consensus, handle received proto message, persist in off-chain db while pending * [slash][node][propose-block] Add verified slashes proposed into the header in block proposal * [slash][shard] Factor out external validator as method on shard state, add double-signature field * [slash][engine] Apply slash, name boolean expression for sorts, use stable sort * [slash] Abstract Ballot results so keep track of both pre and post double sign event * [slash] Fix type errors on test code * [slash] Read from correct rawdb * [slash] Add epoch based guards in CRUD of slashing * [slash] Write to correct cache for slashing candidates * [shard] Use explicit named type of BLS Signature, use convention * [slash] Fix mistake done in refactor, improper header used. Factor out fromSlice to set * [slash][node] Restore newblock to master, try again minimial change * [cx-receipts] Break up one-liner, use SliceStable, not Slice * [network] Finish refactor that makes network message headers once * [network] Simplify creation further of headers write * [slash] Adjust data structure of slash after offline discussion with RJ, Chao * [slash] Still did need signature of the double signature * [consensus] Prepare message does not have block header * [consensus] Soft reset three files to 968517d~1 * [consensus] Begin factor consensus network intended message out with prepare first * [consensus] Factor out Prepared message * [consensus] Factor out announce message creation * [consensus] Committed Message, branch on verify sender key for clearer log * [consensus] Committed Message Factor out * [consensus] Do jenkins MVP of signatures adjustment * [main][slash] Provide YAML config as webhook config for double sign event * [consensus] Adjust signatures, whitespace, lessen GC pressure * [consensus] Remove dead code * [consensus] Factor out commit overloaded message, give commit payload override in construct * [consensus] Fix travis tests * [consensus] Provide block bytes in SubmitVote(quorum.Commit) * [consensus] Factor out noisy sanity checks in BFT, move existing commit check earlier as was before * [quorum] Adjust signatures in quorum * [staking] Adjust after merge from master * [consensus] Finish refactor of consensus * [node] Fix import * [consensus] Fix travis * [consensus] Use origin/master copy of block, fix mistake of pointer to empty byte * [consensus] Less verbose bools * [consensus] Remove unused trailing mutation hook in message construct * [consensus] Address some TODOs on err, comment out double sign
5 years ago
block, _ := contractworker.FinalizeNewBlock(
commitSigs, func() uint64 { return 0 }, common.Address{}, nil, nil,
[slash][consensus] Notice double sign & broadcast, factor out tech debt of consensus (#2152) * [slash] Remove dead interface, associated piping * [slash] Expand out structs * [consensus] Write to a chan when find a case of double-signing, remove dead code * [slash] Broadcast the noticing of a double signing * [rawdb] CRUD for slashing candidates * [slashing][node][proto] Broadcast the slash record after receive from consensus, handle received proto message, persist in off-chain db while pending * [slash][node][propose-block] Add verified slashes proposed into the header in block proposal * [slash][shard] Factor out external validator as method on shard state, add double-signature field * [slash][engine] Apply slash, name boolean expression for sorts, use stable sort * [slash] Abstract Ballot results so keep track of both pre and post double sign event * [slash] Fix type errors on test code * [slash] Read from correct rawdb * [slash] Add epoch based guards in CRUD of slashing * [slash] Write to correct cache for slashing candidates * [shard] Use explicit named type of BLS Signature, use convention * [slash] Fix mistake done in refactor, improper header used. Factor out fromSlice to set * [slash][node] Restore newblock to master, try again minimial change * [cx-receipts] Break up one-liner, use SliceStable, not Slice * [network] Finish refactor that makes network message headers once * [network] Simplify creation further of headers write * [slash] Adjust data structure of slash after offline discussion with RJ, Chao * [slash] Still did need signature of the double signature * [consensus] Prepare message does not have block header * [consensus] Soft reset three files to 968517d~1 * [consensus] Begin factor consensus network intended message out with prepare first * [consensus] Factor out Prepared message * [consensus] Factor out announce message creation * [consensus] Committed Message, branch on verify sender key for clearer log * [consensus] Committed Message Factor out * [consensus] Do jenkins MVP of signatures adjustment * [main][slash] Provide YAML config as webhook config for double sign event * [consensus] Adjust signatures, whitespace, lessen GC pressure * [consensus] Remove dead code * [consensus] Factor out commit overloaded message, give commit payload override in construct * [consensus] Fix travis tests * [consensus] Provide block bytes in SubmitVote(quorum.Commit) * [consensus] Factor out noisy sanity checks in BFT, move existing commit check earlier as was before * [quorum] Adjust signatures in quorum * [staking] Adjust after merge from master * [consensus] Finish refactor of consensus * [node] Fix import * [consensus] Fix travis * [consensus] Use origin/master copy of block, fix mistake of pointer to empty byte * [consensus] Less verbose bools * [consensus] Remove unused trailing mutation hook in message construct * [consensus] Address some TODOs on err, comment out double sign
5 years ago
)
_, err = chain.InsertChain(types.Blocks{block}, true /* verifyHeaders */)
if err != nil {
fmt.Println(err)
}
state = contractworker.GetCurrentState()
fmt.Println("Balances AFTER CALL of faucet contract")
fmt.Println("contract balance:")
fmt.Println(state.GetBalance(faucetContractAddress))
fmt.Println("user address balance")
fmt.Println(state.GetBalance(allRandomUserAddress[0]))
fmt.Println()
fmt.Println("--------- Faucet Contract Call DONE ---------")
}
func playFaucetContract(chain core.BlockChain) {
fundFaucetContract(chain)
callFaucetContractToFundAnAddress(chain)
}
func main() {
genesis := gspec.MustCommit(database)
3 years ago
chain, _ := core.NewBlockChain(database, harmonyState.NewDatabase(database), nil, gspec.Config, chain.Engine(), vm.Config{}, nil)
Fix error sink msg duplication & false positives (#2924) * [types] Add TransactionErrorSink to report failed txs [node] Create ErrorSink handler for unique error msgs Implemented with a LRU cache. [node] Rename ErrorSink to TransactionErrorSink * Rename RPCTransactionError to TransactionError [node] Make tx error sink not return err on Add & Remove [node] Make tx errorSink Contains check take string as tx hash param [errorsink] Move tx error sink into errorsink pkg [errorsink] Rename Errors and Count methods [errorsink] Rename NewTransactionErrorSink to NewTransactionSink [types] Move error sink to core/types * Rename NewTransactionSink to NewTransactionErrorSink * [types] Fix log msg for unfound errors * [types] Rename TransactionError to TransactionErrorReport * [core] Remove RPCTransactionError & refactor tx_pool to use TxErrorSink * [staking] Remove RPCTransactionError * [node] Refactor tx_pool init to use new TxErrorSink * [main] Construct transaction error sink before initing the node * [node] Refactor error sink reporting at RPC layer * [rpc] Refactor returned type of ErrorSink RPCs to 1 type * [core] Remove tx from TxErrorSink on Add to tx_pool * [types] Make NewTransactionErrorSink not return err * [node] Make node.New create error sink * [cmd] Revert to origin main.go * [core] Add TxErrorSink unit test & fix bad ErrExcessiveBLSKeys in tests * [testnet config] Change testnet config to allow for 5*4 external keys * [cmd] Revert main.go to original node instantiation * [rpc] Add GetPoolStats rpc to fetch pending and queued tx counts
5 years ago
txpool := core.NewTxPool(core.DefaultTxPoolConfig, chainConfig, chain, types.NewTransactionErrorSink())
backend := &testWorkerBackend{
db: database,
chain: chain,
txPool: txpool,
}
Abstract transactions in tx pool and add staking transaction to pool with error report (#2236) * [core] Add tx-pool txn interface & update supporting components * Add txn interface (`PoolTransaction`) for tx-pool * Update tx_journal to handle pool's txn interface * Update tx_list to handle pool's txn interface * [staking] Satisfy `PoolTransaction` interface & move error sink types * Implement `Protected`, `ToShardID`, `To`, `Data`, `Value` and `Size` for `StakingTransaction` to satisfy `PoolTransaction` interface * Refactor `Price` to `GasPrice` for `StakingTransaction` to satisfy `PoolTransaction` interface * Move error sink related components to transaction.go * Expose `VerifyBLSKey` and `VerifyBLSKeys` * [core] Generalize tx pool & refactor error sink logic * Refactor txn logic to use `PoolTransaction` and `PoolTransactions` * Add `txPoolErrorReporter` to handle reporting to plainTx and stakingTx error sinks * Remove old & unpayable txs error reports (to error sink) since errs are already reported when adding the txs * Fix known transaction error report when adding txn batches * Add error sink reporting when failed to enqueue txs * [node] Fix error sink & update tx pool interaction * Integrate staking transaction in tx-pool * Remove staking transaction error sink * [hmy api] Integrate staking transactions from tx pool * Remove looking at tx pool for `GetTransactionByHash` * Add `PendingStakingTransactions` and update `PendingTransactions` to only return plainTx * [tests] Update all tests for tx pool txn interface & staking err sink * Update transactions to `PoolTransaction` interface * Remove `CommitTransactions` staking txn error sink * Add basic staking txn tests to tx pool tests * [node] Make all node broadcast staking tx and plain tx * [core + staking] Separate staking msg check and put in tx pool * Move `Validator` specific sanity check into its own method and call said method in `ValidatorWrapper` sanity check * Create staking msg verifiers and preprocessors in `staking_verifier.go` * Remove staking msg verification on all staking msg applications in `state_transition.go` and call new staking msg verifiers & preprocessors * Add staking msg verification to tx pool * Remove `ToShardID` from `PoolTransaction` interface and remove trivial implementation of `ToShardID` in `StakingTransaction`
5 years ago
poolPendingTx := types.PoolTransactions{}
for _, tx := range pendingTxs {
poolPendingTx = append(poolPendingTx, tx.(types.PoolTransaction))
Abstract transactions in tx pool and add staking transaction to pool with error report (#2236) * [core] Add tx-pool txn interface & update supporting components * Add txn interface (`PoolTransaction`) for tx-pool * Update tx_journal to handle pool's txn interface * Update tx_list to handle pool's txn interface * [staking] Satisfy `PoolTransaction` interface & move error sink types * Implement `Protected`, `ToShardID`, `To`, `Data`, `Value` and `Size` for `StakingTransaction` to satisfy `PoolTransaction` interface * Refactor `Price` to `GasPrice` for `StakingTransaction` to satisfy `PoolTransaction` interface * Move error sink related components to transaction.go * Expose `VerifyBLSKey` and `VerifyBLSKeys` * [core] Generalize tx pool & refactor error sink logic * Refactor txn logic to use `PoolTransaction` and `PoolTransactions` * Add `txPoolErrorReporter` to handle reporting to plainTx and stakingTx error sinks * Remove old & unpayable txs error reports (to error sink) since errs are already reported when adding the txs * Fix known transaction error report when adding txn batches * Add error sink reporting when failed to enqueue txs * [node] Fix error sink & update tx pool interaction * Integrate staking transaction in tx-pool * Remove staking transaction error sink * [hmy api] Integrate staking transactions from tx pool * Remove looking at tx pool for `GetTransactionByHash` * Add `PendingStakingTransactions` and update `PendingTransactions` to only return plainTx * [tests] Update all tests for tx pool txn interface & staking err sink * Update transactions to `PoolTransaction` interface * Remove `CommitTransactions` staking txn error sink * Add basic staking txn tests to tx pool tests * [node] Make all node broadcast staking tx and plain tx * [core + staking] Separate staking msg check and put in tx pool * Move `Validator` specific sanity check into its own method and call said method in `ValidatorWrapper` sanity check * Create staking msg verifiers and preprocessors in `staking_verifier.go` * Remove staking msg verification on all staking msg applications in `state_transition.go` and call new staking msg verifiers & preprocessors * Add staking msg verification to tx pool * Remove `ToShardID` from `PoolTransaction` interface and remove trivial implementation of `ToShardID` in `StakingTransaction`
5 years ago
}
backend.txPool.AddLocals(poolPendingTx)
//// Generate a small n-block chain and an uncle block for it
n := 3
if n > 0 {
blocks, _ := chain2.GenerateChain(chainConfig, genesis, chain.Engine(), database, n, func(i int, gen *chain2.BlockGen) {
gen.SetCoinbase(FaucetAddress)
gen.SetShardID(0)
gen.AddTx(pendingTxs[i].(*types.Transaction))
})
if _, err := chain.InsertChain(blocks, true /* verifyHeaders */); err != nil {
log.Fatal(err)
}
}
playFaucetContract(chain)
}