func (db *MemDatabase) Print() { for key, val := range db.db { fmt.Printf("%x(%d): ", key, len(key)) node := ethutil.NewValueFromBytes(val) fmt.Printf("%q\n", node.Interface()) } }
// Returns the object stored at key and the type stored at key // Returns nil if nothing is stored func (s *State) Get(key []byte) (*ethutil.Value, ObjType) { // Fetch data from the trie data := s.trie.Get(string(key)) // Returns the nil type, indicating nothing could be retrieved. // Anything using this function should check for this ret val if data == "" { return nil, NilTy } var typ ObjType val := ethutil.NewValueFromBytes([]byte(data)) // Check the length of the retrieved value. // Len 2 = Account // Len 3 = Contract // Other = invalid for now. If other types emerge, add them here if val.Len() == 2 { typ = AccountTy } else if val.Len() == 3 { typ = ContractTy } else { typ = UnknownTy } return val, typ }
func (s *State) GetContract(addr []byte) *Contract { data := s.trie.Get(string(addr)) if data == "" { return nil } // Whet get contract is called the retrieved value might // be an account. The StateManager uses this to check // to see if the address a tx was sent to is a contract // or an account value := ethutil.NewValueFromBytes([]byte(data)) if value.Len() == 2 { return nil } // build contract contract := NewContractFromBytes(addr, []byte(data)) // Check if there's a cached state for this contract cachedState := s.states[string(addr)] if cachedState != nil { contract.state = cachedState } else { // If it isn't cached, cache the state s.states[string(addr)] = contract.state } return contract }
func ReadMessage(data []byte) (msg *Msg, remaining []byte, done bool, err error) { if len(data) == 0 { return nil, nil, true, nil } if len(data) <= 8 { return nil, remaining, false, errors.New("Invalid message") } // Check if the received 4 first bytes are the magic token if bytes.Compare(MagicToken, data[:4]) != 0 { return nil, nil, false, fmt.Errorf("MagicToken mismatch. Received %v", data[:4]) } messageLength := ethutil.BytesToNumber(data[4:8]) remaining = data[8+messageLength:] if int(messageLength) > len(data[8:]) { return nil, nil, false, fmt.Errorf("message length %d, expected %d", len(data[8:]), messageLength) } message := data[8 : 8+messageLength] decoder := ethutil.NewValueFromBytes(message) // Type of message t := decoder.Get(0).Uint() // Actual data d := decoder.SliceFrom(1) msg = &Msg{ Type: MsgType(t), Data: d, } return }
func (c *Contract) RlpDecode(data []byte) { decoder := ethutil.NewValueFromBytes(data) c.Amount = decoder.Get(0).BigInt() c.Nonce = decoder.Get(1).Uint() c.state = NewState(ethutil.NewTrie(ethutil.Config.Db, decoder.Get(2).Interface())) }
func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value { if int64(len(c.Code)-1) < pc.Int64() { return ethutil.NewValue(0) } return ethutil.NewValueFromBytes([]byte{c.Code[pc.Int64()]}) }
func (bi *BlockInfo) RlpDecode(data []byte) { decoder := ethutil.NewValueFromBytes(data) bi.Number = decoder.Get(0).Uint() bi.Hash = decoder.Get(1).Bytes() bi.Parent = decoder.Get(2).Bytes() }
func (db *LDBDatabase) Print() { iter := db.db.NewIterator(nil, nil) for iter.Next() { key := iter.Key() value := iter.Value() fmt.Printf("%x(%d): ", key, len(key)) node := ethutil.NewValueFromBytes(value) fmt.Printf("%v\n", node) } }
func (p *Peer) pushHandshake() error { data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) pubkey := ethutil.NewValueFromBytes(data).Get(2).Bytes() msg := ethwire.NewMessage(ethwire.MsgHandshakeTy, []interface{}{ uint32(ProtocolVersion), uint32(0), p.Version, byte(p.caps), p.port, pubkey, }) p.QueueMessage(msg) return nil }
func NewKeyRingFromBytes(data []byte) (*KeyRing, error) { var secrets [][]byte it := ethutil.NewValueFromBytes(data).NewIterator() for it.Next() { secret := it.Value().Bytes() secrets = append(secrets, secret) } keyRing, err := NewKeyRingFromSecrets(secrets) if err != nil { return nil, err } return keyRing, nil }
func (c *StateObject) RlpDecode(data []byte) { decoder := ethutil.NewValueFromBytes(data) c.Nonce = decoder.Get(0).Uint() c.Balance = decoder.Get(1).BigInt() c.State = New(ethtrie.New(ethutil.Config.Db, decoder.Get(2).Interface())) c.storage = make(map[string]*ethutil.Value) c.gasPool = new(big.Int) c.CodeHash = decoder.Get(3).Bytes() c.Code, _ = ethutil.Config.Db.Get(c.CodeHash) }
func GetKeyRing(state *State) *KeyRing { if keyRing == nil { keyRing = &KeyRing{} data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) it := ethutil.NewValueFromBytes(data).NewIterator() for it.Next() { v := it.Value() keyRing.Add(NewKeyPairFromValue(v)) } } return keyRing }
// Returns an address from the specified contract's address func contractMemory(state *State, contractAddr []byte, memAddr *big.Int) *big.Int { contract := state.GetContract(contractAddr) if contract == nil { log.Panicf("invalid contract addr %x", contractAddr) } val := state.trie.Get(memAddr.String()) // decode the object as a big integer decoder := ethutil.NewValueFromBytes([]byte(val)) if decoder.IsNil() { return ethutil.BigFalse } return decoder.BigInt() }
func (cache *Cache) Get(key []byte) *ethutil.Value { // First check if the key is the cache if cache.nodes[string(key)] != nil { return cache.nodes[string(key)].Value } // Get the key of the database instead and cache it data, _ := cache.db.Get(key) // Create the cached value value := ethutil.NewValueFromBytes(data) // Create caching node cache.nodes[string(key)] = NewNode(key, value, false) return value }
func NewPeer(conn net.Conn, ethereum *Ethereum, inbound bool) *Peer { data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) pubkey := ethutil.NewValueFromBytes(data).Get(2).Bytes() return &Peer{ outputQueue: make(chan *ethwire.Msg, outputBufferSize), quit: make(chan bool), ethereum: ethereum, conn: conn, inbound: inbound, disconnect: 0, connected: 1, port: 30303, pubkey: pubkey, } }
func (t *Trie) getNode(node interface{}) *ethutil.Value { n := ethutil.NewValue(node) if !n.Get(0).IsNil() { return n } str := n.Str() if len(str) == 0 { return n } else if len(str) < 32 { return ethutil.NewValueFromBytes([]byte(str)) } data := t.cache.Get(n.Bytes()) return data }
func (i *Console) ParseInput(input string) bool { scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Split(bufio.ScanWords) count := 0 var tokens []string for scanner.Scan() { count++ tokens = append(tokens, scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } if len(tokens) == 0 { return true } err := i.ValidateInput(tokens[0], count-1) if err != nil { fmt.Println(err) } else { switch tokens[0] { case "update": i.trie.Update(tokens[1], tokens[2]) i.PrintRoot() case "get": fmt.Println(i.trie.Get(tokens[1])) case "root": i.PrintRoot() case "rawroot": fmt.Println(i.trie.Root) case "print": i.db.Print() case "dag": fmt.Println(ethchain.DaggerVerify(ethutil.Big(tokens[1]), // hash ethutil.BigPow(2, 36), // diff ethutil.Big(tokens[2]))) // nonce case "decode": value := ethutil.NewValueFromBytes([]byte(tokens[1])) fmt.Println(value) case "getaddr": encoded, _ := hex.DecodeString(tokens[1]) addr := i.ethereum.BlockManager.BlockChain().CurrentBlock.GetAddr(encoded) fmt.Println("addr:", addr) case "block": encoded, _ := hex.DecodeString(tokens[1]) block := i.ethereum.BlockManager.BlockChain().GetBlock(encoded) fmt.Println(block) case "say": i.ethereum.Broadcast(ethwire.MsgTalkTy, []interface{}{tokens[1]}) case "addp": i.ethereum.ConnectToPeer(tokens[1]) case "pcount": fmt.Println("peers:", i.ethereum.Peers().Len()) case "encode": fmt.Printf("%q\n", ethutil.Encode(tokens[1])) case "tx": recipient, err := hex.DecodeString(tokens[1]) if err != nil { fmt.Println("recipient err:", err) } else { tx := ethchain.NewTransaction(recipient, ethutil.Big(tokens[2]), []string{""}) data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) keyRing := ethutil.NewValueFromBytes(data) tx.Sign(keyRing.Get(0).Bytes()) fmt.Printf("%x\n", tx.Hash()) i.ethereum.TxPool.QueueTransaction(tx) } case "gettx": addr, _ := hex.DecodeString(tokens[1]) data, _ := ethutil.Config.Db.Get(addr) if len(data) != 0 { decoder := ethutil.NewValueFromBytes(data) fmt.Println(decoder) } else { fmt.Println("gettx: tx not found") } case "contract": contract := ethchain.NewTransaction([]byte{}, ethutil.Big(tokens[1]), []string{"PUSH", "1234"}) fmt.Printf("%x\n", contract.Hash()) i.ethereum.TxPool.QueueTransaction(contract) case "exit", "quit", "q": return false case "help": fmt.Printf("COMMANDS:\n" + "\033[1m= DB =\033[0m\n" + "update KEY VALUE - Updates/Creates a new value for the given key\n" + "get KEY - Retrieves the given key\n" + "root - Prints the hex encoded merkle root\n" + "rawroot - Prints the raw merkle root\n" + "block HASH - Prints the block\n" + "getaddr ADDR - Prints the account associated with the address\n" + "\033[1m= Dagger =\033[0m\n" + "dag HASH NONCE - Verifies a nonce with the given hash with dagger\n" + "\033[1m= Encoding =\033[0m\n" + "decode STR\n" + "encode STR\n" + "\033[1m= Other =\033[0m\n" + "addp HOST:PORT\n" + "tx TO AMOUNT\n" + "contract AMOUNT\n") default: fmt.Println("Unknown command:", tokens[0]) } } return true }
func (c *StateObject) GetAddr(addr []byte) *ethutil.Value { return ethutil.NewValueFromBytes([]byte(c.State.Trie.Get(string(addr)))) }
func (tx *Transaction) RlpDecode(data []byte) { tx.RlpValueDecode(ethutil.NewValueFromBytes(data)) }
func (c *Contract) Addr(addr []byte) *ethutil.Value { return ethutil.NewValueFromBytes([]byte(c.state.trie.Get(string(addr)))) }
func (a *Account) RlpDecode(data []byte) { decoder := ethutil.NewValueFromBytes(data) a.Amount = decoder.Get(0).BigInt() a.Nonce = decoder.Get(1).Uint() }
func main() { Init() runtime.GOMAXPROCS(runtime.NumCPU()) ethchain.InitFees() ethutil.ReadConfig(DataDir) ethutil.Config.Seed = UseSeed // Instantiated a eth stack ethereum, err := eth.New(eth.CapDefault, UseUPnP) if err != nil { log.Println("eth start err:", err) return } ethereum.Port = OutboundPort if GenAddr { fmt.Println("This action overwrites your old private key. Are you sure? (y/n)") var r string fmt.Scanln(&r) for ; ; fmt.Scanln(&r) { if r == "n" || r == "y" { break } else { fmt.Printf("Yes or no?", r) } } if r == "y" { utils.CreateKeyPair(true) } os.Exit(0) } else { if len(ImportKey) > 0 { fmt.Println("This action overwrites your old private key. Are you sure? (y/n)") var r string fmt.Scanln(&r) for ; ; fmt.Scanln(&r) { if r == "n" || r == "y" { break } else { fmt.Printf("Yes or no?", r) } } if r == "y" { utils.ImportPrivateKey(ImportKey) os.Exit(0) } } else { utils.CreateKeyPair(false) } } if ExportKey { key := ethutil.Config.Db.GetKeys()[0] fmt.Printf("%x\n", key.PrivateKey) os.Exit(0) } if ShowGenesis { fmt.Println(ethereum.BlockChain().Genesis()) os.Exit(0) } log.Printf("Starting Ethereum v%s\n", ethutil.Config.Ver) // Set the max peers ethereum.MaxPeers = MaxPeer if StartConsole { err := os.Mkdir(ethutil.Config.ExecPath, os.ModePerm) // Error is OK if the error is ErrExist if err != nil && !os.IsExist(err) { log.Panic("Unable to create EXECPATH:", err) } console := NewConsole(ethereum) go console.Start() } RegisterInterupts(ethereum) ethereum.Start() if StartMining { log.Printf("Miner started\n") // Fake block mining. It broadcasts a new block every 5 seconds go func() { pow := ðchain.EasyPow{} data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) keyRing := ethutil.NewValueFromBytes(data) addr := keyRing.Get(1).Bytes() for { txs := ethereum.TxPool().Flush() // Create a new block which we're going to mine block := ethereum.BlockChain().NewBlock(addr, txs) log.Println("Mining on new block. Includes", len(block.Transactions()), "transactions") // Apply all transactions to the block ethereum.StateManager().ApplyTransactions(block, block.Transactions()) ethereum.StateManager().Prepare(block.State(), block.State()) ethereum.StateManager().AccumelateRewards(block) // Search the nonce block.Nonce = pow.Search(block) ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{block.Value().Val}) ethereum.StateManager().PrepareDefault(block) err := ethereum.StateManager().ProcessBlock(block) if err != nil { log.Println(err) } else { log.Println("\n+++++++ MINED BLK +++++++\n", ethereum.BlockChain().CurrentBlock) log.Printf("🔨 Mined block %x\n", block.Hash()) } } }() } // Wait for shutdown ethereum.WaitForShutdown() }
func (block *Block) RlpDecode(data []byte) { rlpValue := ethutil.NewValueFromBytes(data) block.RlpValueDecode(rlpValue) }