func TestBox(t *testing.T) { prv1 := ToECDSA(common.Hex2Bytes("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")) prv2 := ToECDSA(common.Hex2Bytes("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")) pub2 := ToECDSAPub(common.Hex2Bytes("04bd27a63c91fe3233c5777e6d3d7b39204d398c8f92655947eb5a373d46e1688f022a1632d264725cbc7dc43ee1cfebde42fa0a86d08b55d2acfbb5e9b3b48dc5")) message := []byte("Hello, world.") ct, err := Encrypt(pub2, message) if err != nil { fmt.Println(err.Error()) t.FailNow() } pt, err := Decrypt(prv2, ct) if err != nil { fmt.Println(err.Error()) t.FailNow() } if !bytes.Equal(pt, message) { fmt.Println("ecies: plaintext doesn't match message") t.FailNow() } _, err = Decrypt(prv1, pt) if err == nil { fmt.Println("ecies: encryption should not have succeeded") t.FailNow() } }
func run(ctx *cli.Context) { vm.Debug = ctx.GlobalBool(DebugFlag.Name) vm.ForceJit = ctx.GlobalBool(ForceJitFlag.Name) vm.EnableJit = !ctx.GlobalBool(DisableJitFlag.Name) glog.SetToStderr(true) db, _ := ethdb.NewMemDatabase() statedb := state.New(common.Hash{}, db) sender := statedb.CreateAccount(common.StringToAddress("sender")) receiver := statedb.CreateAccount(common.StringToAddress("receiver")) receiver.SetCode(common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name))) vmenv := NewEnv(statedb, common.StringToAddress("evmuser"), common.Big(ctx.GlobalString(ValueFlag.Name))) tstart := time.Now() ret, e := vmenv.Call( sender, receiver.Address(), common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)), common.Big(ctx.GlobalString(GasFlag.Name)), common.Big(ctx.GlobalString(PriceFlag.Name)), common.Big(ctx.GlobalString(ValueFlag.Name)), ) vmdone := time.Since(tstart) if ctx.GlobalBool(DumpFlag.Name) { fmt.Println(string(statedb.Dump())) } vm.StdErrFormat(vmenv.StructLogs()) if ctx.GlobalBool(SysStatFlag.Name) { var mem runtime.MemStats runtime.ReadMemStats(&mem) fmt.Printf("vm took %v\n", vmdone) fmt.Printf(`alloc: %d tot alloc: %d no. malloc: %d heap alloc: %d heap objs: %d num gc: %d `, mem.Alloc, mem.TotalAlloc, mem.Mallocs, mem.HeapAlloc, mem.HeapObjects, mem.NumGC) } fmt.Printf("OUT: 0x%x", ret) if e != nil { fmt.Printf(" error: %v", e) } fmt.Println() }
func checkLogs(tlog []Log, logs state.Logs) error { if len(tlog) != len(logs) { return fmt.Errorf("log length mismatch. Expected %d, got %d", len(tlog), len(logs)) } else { for i, log := range tlog { if common.HexToAddress(log.AddressF) != logs[i].Address { return fmt.Errorf("log address expected %v got %x", log.AddressF, logs[i].Address) } if !bytes.Equal(logs[i].Data, common.FromHex(log.DataF)) { return fmt.Errorf("log data expected %v got %x", log.DataF, logs[i].Data) } if len(log.TopicsF) != len(logs[i].Topics) { return fmt.Errorf("log topics length expected %d got %d", len(log.TopicsF), logs[i].Topics) } else { for j, topic := range log.TopicsF { if common.HexToHash(topic) != logs[i].Topics[j] { return fmt.Errorf("log topic[%d] expected %v got %x", j, topic, logs[i].Topics[j]) } } } genBloom := common.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256) if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) { return fmt.Errorf("bloom mismatch") } } } return nil }
func (self *Object) StorageString(str string) []byte { if common.IsHex(str) { return self.storage(common.Hex2Bytes(str[2:])) } else { return self.storage(common.RightPadBytes([]byte(str), 32)) } }
func TestDelete(t *testing.T) { trie := NewEmpty() vals := []struct{ k, v string }{ {"do", "verb"}, {"ether", "wookiedoo"}, {"horse", "stallion"}, {"shaman", "horse"}, {"doge", "coin"}, {"ether", ""}, {"dog", "puppy"}, {"shaman", ""}, } for _, val := range vals { if val.v != "" { trie.UpdateString(val.k, val.v) } else { trie.DeleteString(val.k) } } hash := trie.Hash() exp := common.Hex2Bytes("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84") if !bytes.Equal(hash, exp) { t.Errorf("expected %x got %x", exp, hash) } }
func TestSecureDelete(t *testing.T) { trie := NewEmptySecure() vals := []struct{ k, v string }{ {"do", "verb"}, {"ether", "wookiedoo"}, {"horse", "stallion"}, {"shaman", "horse"}, {"doge", "coin"}, {"ether", ""}, {"dog", "puppy"}, {"shaman", ""}, } for _, val := range vals { if val.v != "" { trie.UpdateString(val.k, val.v) } else { trie.DeleteString(val.k) } } hash := trie.Hash() exp := common.Hex2Bytes("29b235a58c3c25ab83010c327d5932bcf05324b7d6b1185e650798034783ca9d") if !bytes.Equal(hash, exp) { t.Errorf("expected %x got %x", exp, hash) } }
func (self Log) Topics() [][]byte { t := make([][]byte, len(self.TopicsF)) for i, topic := range self.TopicsF { t[i] = common.Hex2Bytes(topic) } return t }
func Test0Key(t *testing.T) { t.Skip() key := common.Hex2Bytes("1111111111111111111111111111111111111111111111111111111111111111") p, err := secp256k1.GeneratePubKey(key) addr := Sha3(p[1:])[12:] fmt.Printf("%x\n", p) fmt.Printf("%v %x\n", err, addr) }
func StateObjectFromAccount(db common.Database, addr string, account Account) *state.StateObject { obj := state.NewStateObject(common.HexToAddress(addr), db) obj.SetBalance(common.Big(account.Balance)) if common.IsHex(account.Code) { account.Code = account.Code[2:] } obj.SetCode(common.Hex2Bytes(account.Code)) obj.SetNonce(common.Big(account.Nonce).Uint64()) return obj }
func TestInsert(t *testing.T) { trie := NewEmpty() trie.UpdateString("doe", "reindeer") trie.UpdateString("dog", "puppy") trie.UpdateString("dogglesworth", "cat") exp := common.Hex2Bytes("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3") root := trie.Hash() if !bytes.Equal(root, exp) { t.Errorf("exp %x got %x", exp, root) } trie = NewEmpty() trie.UpdateString("A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") exp = common.Hex2Bytes("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab") root = trie.Hash() if !bytes.Equal(root, exp) { t.Errorf("exp %x got %x", exp, root) } }
func TestSet(t *testing.T) { a := Uint(0) b := Uint(10) a.Set(b) if a.num.Cmp(b.num) != 0 { t.Error("didn't compare", a, b) } c := Uint(0).SetBytes(common.Hex2Bytes("0a")) if c.num.Cmp(big.NewInt(10)) != 0 { t.Error("c set bytes failed.") } }
func TestRecipientEmpty(t *testing.T) { _, addr := defaultTestKey() tx, err := decodeTx(common.Hex2Bytes("f8498080808080011ca09b16de9d5bdee2cf56c28d16275a4da68cd30273e2525f3959f5d62557489921a0372ebd8fb3345f7db7b5a86d42e24d36e983e259b0664ceb8c227ec9af572f3d")) if err != nil { t.Error(err) t.FailNow() } from, err := tx.From() if err != nil { t.Error(err) t.FailNow() } if addr != from { t.Error("derived address doesn't match") } }
func TestRecipientNormal(t *testing.T) { _, addr := defaultTestKey() tx, err := decodeTx(common.Hex2Bytes("f85d80808094000000000000000000000000000000000000000080011ca0527c0d8f5c63f7b9f41324a7c8a563ee1190bcbf0dac8ab446291bdbf32f5c79a0552c4ef0a09a04395074dab9ed34d3fbfb843c2f2546cc30fe89ec143ca94ca6")) if err != nil { t.Error(err) t.FailNow() } from, err := tx.From() if err != nil { t.Error(err) t.FailNow() } if addr != from { t.Error("derived address doesn't match") } }
func main() { code, err := ioutil.ReadAll(os.Stdin) if err != nil { fmt.Println(err) os.Exit(1) } code = common.Hex2Bytes(string(code[:len(code)-1])) fmt.Printf("%x\n", code) for pc := uint64(0); pc < uint64(len(code)); pc++ { op := vm.OpCode(code[pc]) fmt.Printf("%-5d %v", pc, op) switch op { case vm.PUSH1, vm.PUSH2, vm.PUSH3, vm.PUSH4, vm.PUSH5, vm.PUSH6, vm.PUSH7, vm.PUSH8, vm.PUSH9, vm.PUSH10, vm.PUSH11, vm.PUSH12, vm.PUSH13, vm.PUSH14, vm.PUSH15, vm.PUSH16, vm.PUSH17, vm.PUSH18, vm.PUSH19, vm.PUSH20, vm.PUSH21, vm.PUSH22, vm.PUSH23, vm.PUSH24, vm.PUSH25, vm.PUSH26, vm.PUSH27, vm.PUSH28, vm.PUSH29, vm.PUSH30, vm.PUSH31, vm.PUSH32: a := uint64(op) - uint64(vm.PUSH1) + 1 fmt.Printf(" => %x", code[pc+1:pc+1+a]) pc += a } fmt.Println() } }
// from bcValidBlockTest.json, "SimpleTx" func TestBlockEncoding(t *testing.T) { blockEnc := common.FromHex("f90260f901f9a083cafc574e1f51ba9dc0568fc617a08ea2429fb384059c972f13b19fa1c8dd55a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017a05fe50b260da6308036625b850b5d6ced6d0a9f814c0688bc91ffb7b7a3a54b67a0bc37d79753ad738a6dac4921e57392f145d8887476de3f783dfa7edae9283e52b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefd8825208845506eb0780a0bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff49888a13a5a8c8f2bb1c4f861f85f800a82c35094095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba09bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094fa08a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b1c0") var block Block if err := rlp.DecodeBytes(blockEnc, &block); err != nil { t.Fatal("decode error: ", err) } check := func(f string, got, want interface{}) { if !reflect.DeepEqual(got, want) { t.Errorf("%s mismatch: got %v, want %v", f, got, want) } } check("Difficulty", block.Difficulty(), big.NewInt(131072)) check("GasLimit", block.GasLimit(), big.NewInt(3141592)) check("GasUsed", block.GasUsed(), big.NewInt(21000)) check("Coinbase", block.Coinbase(), common.HexToAddress("8888f1f195afa192cfee860698584c030f4c9db1")) check("MixDigest", block.MixDigest(), common.HexToHash("bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff498")) check("Root", block.Root(), common.HexToHash("ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017")) check("Hash", block.Hash(), common.HexToHash("0a5843ac1cb04865017cb35a57b50b07084e5fcee39b5acadade33149f4fff9e")) check("Nonce", block.Nonce(), uint64(0xa13a5a8c8f2bb1c4)) check("Time", block.Time(), big.NewInt(1426516743)) check("Size", block.Size(), common.StorageSize(len(blockEnc))) tx1 := NewTransaction(0, common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), big.NewInt(10), big.NewInt(50000), big.NewInt(10), nil) tx1, _ = tx1.WithSignature(common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b100")) check("len(Transactions)", len(block.Transactions()), 1) check("Transactions[0].Hash", block.Transactions()[0].Hash(), tx1.Hash()) ourBlockEnc, err := rlp.EncodeToBytes(&block) if err != nil { t.Fatal("encode error: ", err) } if !bytes.Equal(ourBlockEnc, blockEnc) { t.Errorf("encoded block mismatch:\ngot: %x\nwant: %x", ourBlockEnc, blockEnc) } }
// HashToUrl(contenthash) resolves the url for contenthash using UrlHint // resolution is costless non-transactional // implemented as direct retrieval from db // if we use content addressed storage, this step is no longer necessary func (self *Registrar) HashToUrl(chash common.Hash) (uri string, err error) { // look up in URL reg var str string = " " var idx uint32 for len(str) > 0 { mapaddr := storageMapping(storageIdx2Addr(1), chash[:]) key := storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(idx))) hex := self.backend.StorageAt(UrlHintAddr[2:], key) str = string(common.Hex2Bytes(hex[2:])) l := 0 for (l < len(str)) && (str[l] == 0) { l++ } str = str[l:] uri = uri + str idx++ } if len(uri) == 0 { err = fmt.Errorf("GetURLhint: URL hint not found for '%v'", chash.Hex()) } return }
for i := 0; i < b.N; i++ { context := NewContext(sender, sender, big.NewInt(100), big.NewInt(10000), big.NewInt(0)) context.Code = test.code context.CodeAddr = &common.Address{} _, err := New(env).Run(context, test.input) if err != nil { b.Error(err) b.FailNow() } } } var benchmarks = map[string]vmBench{ "pushes": vmBench{ false, false, false, common.Hex2Bytes("600a600a01600a600a01600a600a01600a600a01600a600a01600a600a01600a600a01600a600a01600a600a01600a600a01"), nil, }, } func BenchmarkPushes(b *testing.B) { runVmBench(benchmarks["pushes"], b) } type Env struct { gasLimit *big.Int depth int } func NewEnv() *Env { return &Env{big.NewInt(10000), 0} }
func (tx *tx) UnmarshalJSON(b []byte) (err error) { var fields map[string]interface{} if err := json.Unmarshal(b, &fields); err != nil { return shared.NewDecodeParamError(err.Error()) } var ( nonce uint64 to common.Address amount = new(big.Int).Set(common.Big0) gasLimit = new(big.Int).Set(common.Big0) gasPrice = new(big.Int).Set(common.Big0) data []byte contractCreation = true ) if val, found := fields["Hash"]; found { if hashVal, ok := val.(string); ok { tx.Hash = hashVal } } if val, found := fields["To"]; found { if strVal, ok := val.(string); ok && len(strVal) > 0 { tx.To = strVal to = common.HexToAddress(strVal) contractCreation = false } } if val, found := fields["From"]; found { if strVal, ok := val.(string); ok { tx.From = strVal } } if val, found := fields["Nonce"]; found { if strVal, ok := val.(string); ok { tx.Nonce = strVal if nonce, err = strconv.ParseUint(strVal, 10, 64); err != nil { return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.Nonce - %v", err)) } } } else { return shared.NewDecodeParamError("tx.Nonce not found") } var parseOk bool if val, found := fields["Value"]; found { if strVal, ok := val.(string); ok { tx.Value = strVal if _, parseOk = amount.SetString(strVal, 0); !parseOk { return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.Amount - %v", err)) } } } if val, found := fields["Data"]; found { if strVal, ok := val.(string); ok { tx.Data = strVal if strings.HasPrefix(strVal, "0x") { data = common.Hex2Bytes(strVal[2:]) } else { data = common.Hex2Bytes(strVal) } } } if val, found := fields["GasLimit"]; found { if strVal, ok := val.(string); ok { tx.GasLimit = strVal if _, parseOk = gasLimit.SetString(strVal, 0); !parseOk { return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.GasLimit - %v", err)) } } } if val, found := fields["GasPrice"]; found { if strVal, ok := val.(string); ok { tx.GasPrice = strVal if _, parseOk = gasPrice.SetString(strVal, 0); !parseOk { return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.GasPrice - %v", err)) } } } if contractCreation { tx.tx = types.NewContractCreation(nonce, amount, gasLimit, gasPrice, data) } else { tx.tx = types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) } return nil }
func defaultTestKey() (*ecdsa.PrivateKey, common.Address) { key := crypto.ToECDSA(common.Hex2Bytes("45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8")) addr := crypto.PubkeyToAddress(key.PublicKey) return key, addr }
emptyTx = NewTransaction( 0, common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, ) rightvrsTx, _ = NewTransaction( 3, common.HexToAddress("b94f5374fce5edbc8e2a8697c15331677e6ebf0b"), big.NewInt(10), big.NewInt(2000), big.NewInt(1), common.FromHex("5544"), ).WithSignature( common.Hex2Bytes("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a301"), ) ) func TestTransactionSigHash(t *testing.T) { if emptyTx.SigHash() != common.HexToHash("c775b99e7ad12f50d819fcd602390467e28141316969f4b57f0626f74fe3b386") { t.Errorf("empty transaction hash mismatch, got %x", emptyTx.Hash()) } if rightvrsTx.SigHash() != common.HexToHash("fe7a79529ed5f7c3375d06b26b186a8644e0e16c373d7a12be41c62d6042b77a") { t.Errorf("RightVRS transaction hash mismatch, got %x", rightvrsTx.Hash()) } } func TestTransactionEncode(t *testing.T) { txb, err := rlp.EncodeToBytes(rightvrsTx) if err != nil {
// Returns the unsigned version of i func (i *Number) Uint256() *Number { return Uint(0).Set(i) } // Returns the index of the first bit that's set to 1 func (i *Number) FirstBitSet() int { for j := 0; j < i.num.BitLen(); j++ { if i.num.Bit(j) > 0 { return j } } return i.num.BitLen() } // Variables var ( Zero = Uint(0) One = Uint(1) Two = Uint(2) MaxUint256 = Uint(0).SetBytes(common.Hex2Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) MinOne = Int(-1) // "typedefs" Uint = Uint256 Int = Int256 )
// WriteGenesisBlock writes the genesis block to the database as block number 0 func WriteGenesisBlock(chainDb common.Database, reader io.Reader) (*types.Block, error) { contents, err := ioutil.ReadAll(reader) if err != nil { return nil, err } var genesis struct { Nonce string Timestamp string ParentHash string ExtraData string GasLimit string Difficulty string Mixhash string Coinbase string Alloc map[string]struct { Code string Storage map[string]string Balance string } } if err := json.Unmarshal(contents, &genesis); err != nil { return nil, err } statedb := state.New(common.Hash{}, chainDb) for addr, account := range genesis.Alloc { address := common.HexToAddress(addr) statedb.AddBalance(address, common.String2Big(account.Balance)) statedb.SetCode(address, common.Hex2Bytes(account.Code)) for key, value := range account.Storage { statedb.SetState(address, common.HexToHash(key), common.HexToHash(value)) } } statedb.SyncObjects() difficulty := common.String2Big(genesis.Difficulty) block := types.NewBlock(&types.Header{ Nonce: types.EncodeNonce(common.String2Big(genesis.Nonce).Uint64()), Time: common.String2Big(genesis.Timestamp), ParentHash: common.HexToHash(genesis.ParentHash), Extra: common.FromHex(genesis.ExtraData), GasLimit: common.String2Big(genesis.GasLimit), Difficulty: difficulty, MixDigest: common.HexToHash(genesis.Mixhash), Coinbase: common.HexToAddress(genesis.Coinbase), Root: statedb.Root(), }, nil, nil, nil) block.Td = difficulty if block := GetBlockByHash(chainDb, block.Hash()); block != nil { glog.V(logger.Info).Infoln("Genesis block already in chain. Writing canonical number") err := WriteCanonNumber(chainDb, block) if err != nil { return nil, err } return block, nil } statedb.Sync() err = WriteBlock(chainDb, block) if err != nil { return nil, err } err = WriteHead(chainDb, block) if err != nil { return nil, err } return block, nil }
) const ( testSolcPath = "" solcVersion = "0.9.23" testKey = "e6fab74a43941f82d89cb7faa408e227cdad3153c4720e540e855c19b15e6674" testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" testBalance = "10000000000000000000" // of empty string testHash = "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" ) var ( versionRE = regexp.MustCompile(strconv.Quote(`"compilerVersion":"` + solcVersion + `"`)) testNodeKey = crypto.ToECDSA(common.Hex2Bytes("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")) testGenesis = `{"` + testAddress[2:] + `": {"balance": "` + testBalance + `"}}` ) type testjethre struct { *jsre lastConfirm string ds *docserver.DocServer } func (self *testjethre) UnlockAccount(acc []byte) bool { err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(acc), "") if err != nil { panic("unable to unlock") } return true
func (self Log) Address() []byte { return common.Hex2Bytes(self.AddressF) }
func (self Log) Data() []byte { return common.Hex2Bytes(self.DataF) }