// validate and queue transactions. func (self *TxPool) add(tx *types.Transaction) error { hash := tx.Hash() if self.pending[hash] != nil { return fmt.Errorf("Known transaction (%x)", hash[:4]) } err := self.validateTx(tx) if err != nil { return err } self.queueTx(hash, tx) if glog.V(logger.Debug) { var toname string if to := tx.To(); to != nil { toname = common.Bytes2Hex(to[:4]) } else { toname = "[NEW_CONTRACT]" } // we can ignore the error here because From is // verified in ValidateTransaction. f, _ := tx.From() from := common.Bytes2Hex(f[:4]) glog.Infof("(t) %x => %s (%v) %x\n", from, toname, tx.Value, hash) } return nil }
func sendBadBlockReport(block *types.Block, err error) { if !EnableBadBlockReporting { return } var ( blockRLP, _ = rlp.EncodeToBytes(block) params = map[string]interface{}{ "block": common.Bytes2Hex(blockRLP), "blockHash": block.Hash().Hex(), "errortype": err.Error(), "client": "go", } ) if !block.ReceivedAt.IsZero() { params["receivedAt"] = block.ReceivedAt.UTC().String() } if p, ok := block.ReceivedFrom.(*peer); ok { params["receivedFrom"] = map[string]interface{}{ "enode": fmt.Sprintf("enode://%x@%v", p.ID(), p.RemoteAddr()), "name": p.Name(), "protocolVersion": p.version, } } jsonStr, _ := json.Marshal(map[string]interface{}{"method": "eth_badBlock", "id": "1", "jsonrpc": "2.0", "params": []interface{}{params}}) client := http.Client{Timeout: 8 * time.Second} resp, err := client.Post(badBlocksURL, "application/json", bytes.NewReader(jsonStr)) if err != nil { glog.V(logger.Debug).Infoln(err) return } glog.V(logger.Debug).Infof("Bad Block Report posted (%d)", resp.StatusCode) resp.Body.Close() }
func encodeName(name string, index uint8) (string, string) { extra := common.Bytes2Hex([]byte(name)) if len(name) > 32 { return fmt.Sprintf("%064x", index), extra } return extra + falseHex[len(extra):], "" }
// UnlockAccount asks the user agent for the user password and tries to unlock the account. // It will try 3 attempts before giving up. func (fe *RemoteFrontend) UnlockAccount(address []byte) bool { if !fe.enabled { return false } err := fe.send(AskPasswordMethod, common.Bytes2Hex(address)) if err != nil { glog.V(logger.Error).Infof("Unable to send password request to agent - %v\n", err) return false } passwdRes, err := fe.recv() if err != nil { glog.V(logger.Error).Infof("Unable to recv password response from agent - %v\n", err) return false } if passwd, ok := passwdRes.Result.(string); ok { err = fe.mgr.Unlock(common.BytesToAddress(address), passwd) } if err == nil { return true } glog.V(logger.Debug).Infoln("3 invalid account unlock attempts") return false }
func (self *ethApi) SignTransaction(req *shared.Request) (interface{}, error) { args := new(NewTxArgs) if err := self.codec.Decode(req.Params, &args); err != nil { return nil, shared.NewDecodeParamError(err.Error()) } // nonce may be nil ("guess" mode) var nonce string if args.Nonce != nil { nonce = args.Nonce.String() } var gas, price string if args.Gas != nil { gas = args.Gas.String() } if args.GasPrice != nil { price = args.GasPrice.String() } tx, err := self.xeth.SignTransaction(args.From, args.To, nonce, args.Value.String(), gas, price, args.Data) if err != nil { return nil, err } data, err := rlp.EncodeToBytes(tx) if err != nil { return nil, err } return JsonTransaction{"0x" + common.Bytes2Hex(data), newTx(tx)}, nil }
func (self *StateDB) RawDump() Dump { dump := Dump{ Root: common.Bytes2Hex(self.trie.Root()), Accounts: make(map[string]DumpAccount), } it := self.trie.Iterator() for it.Next() { addr := self.trie.GetKey(it.Key) var data Account if err := rlp.DecodeBytes(it.Value, &data); err != nil { panic(err) } obj := newObject(nil, common.BytesToAddress(addr), data, nil) account := DumpAccount{ Balance: data.Balance.String(), Nonce: data.Nonce, Root: common.Bytes2Hex(data.Root[:]), CodeHash: common.Bytes2Hex(data.CodeHash), Code: common.Bytes2Hex(obj.Code(self.db)), Storage: make(map[string]string), } storageIt := obj.getTrie(self.db).Iterator() for storageIt.Next() { account.Storage[common.Bytes2Hex(self.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value) } dump.Accounts[common.Bytes2Hex(addr)] = account } return dump }
func (d *hexnum) String() string { // Get hex string from bytes out := common.Bytes2Hex(d.data) // Trim leading 0s out = strings.TrimLeft(out, "0") // Output "0x0" when value is 0 if len(out) == 0 { out = "0" } return "0x" + out }
// registers some content hash to a key/code hash // e.g., the contract Info combined Json Doc's ContentHash // to CodeHash of a contract or hash of a domain func (self *Registrar) SetHashToHash(address common.Address, codehash, dochash common.Hash) (txh string, err error) { if zero.MatchString(HashRegAddr) { return "", fmt.Errorf("HashReg address is not set") } _, err = self.SetOwner(address) if err != nil { return } codehex := common.Bytes2Hex(codehash[:]) dochex := common.Bytes2Hex(dochash[:]) data := registerContentHashAbi + codehex + dochex glog.V(logger.Detail).Infof("SetHashToHash data: %s sent to %v\n", data, HashRegAddr) return self.backend.Transact( address.Hex(), HashRegAddr, "", "", "", "", data, ) }
func (self *StateDB) RawDump() World { world := World{ Root: common.Bytes2Hex(self.trie.Root()), Accounts: make(map[string]Account), } it := self.trie.Iterator() for it.Next() { addr := self.trie.GetKey(it.Key) stateObject := NewStateObjectFromBytes(common.BytesToAddress(addr), it.Value, self.db) account := Account{Balance: stateObject.balance.String(), Nonce: stateObject.nonce, Root: common.Bytes2Hex(stateObject.Root()), CodeHash: common.Bytes2Hex(stateObject.codeHash)} account.Storage = make(map[string]string) storageIt := stateObject.trie.Iterator() for storageIt.Next() { account.Storage[common.Bytes2Hex(self.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value) } world.Accounts[common.Bytes2Hex(addr)] = account } return world }
func (self *NatSpec) makeAbi2method(abiKey [8]byte) (meth *method) { for signature, m := range self.userDoc.Methods { name := strings.Split(signature, "(")[0] hash := []byte(common.Bytes2Hex(crypto.Sha3([]byte(signature)))) var key [8]byte copy(key[:], hash[:8]) if bytes.Equal(key[:], abiKey[:]) { meth = m meth.name = name return } } return }
// SetUrlToHash(from, hash, url) registers a url to a content hash so that the content can be fetched // address is used as sender for the transaction and will be the owner of a new // registry entry on first time use // FIXME: silently doing nothing if sender is not the owner // note that with content addressed storage, this step is no longer necessary func (self *Registrar) SetUrlToHash(address common.Address, hash common.Hash, url string) (txh string, err error) { if zero.MatchString(UrlHintAddr) { return "", fmt.Errorf("UrlHint address is not set") } hashHex := common.Bytes2Hex(hash[:]) var urlHex string urlb := []byte(url) var cnt byte n := len(urlb) for n > 0 { if n > 32 { n = 32 } urlHex = common.Bytes2Hex(urlb[:n]) urlb = urlb[n:] n = len(urlb) bcnt := make([]byte, 32) bcnt[31] = cnt data := registerUrlAbi + hashHex + common.Bytes2Hex(bcnt) + common.Bytes2Hex(common.Hex2BytesFixed(urlHex, 32)) txh, err = self.backend.Transact( address.Hex(), UrlHintAddr, "", "", "", "", data, ) if err != nil { return } cnt++ } return }
func newTx(t *types.Transaction) *tx { from, _ := t.From() var to string if t := t.To(); t != nil { to = t.Hex() } return &tx{ tx: t, To: to, From: from.Hex(), Value: t.Value().String(), Nonce: strconv.Itoa(int(t.Nonce())), Data: "0x" + common.Bytes2Hex(t.Data()), GasLimit: t.Gas().String(), GasPrice: t.GasPrice().String(), Hash: t.Hash().Hex(), } }
func (test *BlockTest) ValidateImportedHeaders(cm *core.BlockChain, validBlocks []btBlock) error { // to get constant lookup when verifying block headers by hash (some tests have many blocks) bmap := make(map[string]btBlock, len(test.Json.Blocks)) for _, b := range validBlocks { bmap[b.BlockHeader.Hash] = b } // iterate over blocks backwards from HEAD and validate imported // headers vs test file. some tests have reorgs, and we import // block-by-block, so we can only validate imported headers after // all blocks have been processed by ChainManager, as they may not // be part of the longest chain until last block is imported. for b := cm.CurrentBlock(); b != nil && b.NumberU64() != 0; b = cm.GetBlock(b.Header().ParentHash) { bHash := common.Bytes2Hex(b.Hash().Bytes()) // hex without 0x prefix if err := validateHeader(bmap[bHash].BlockHeader, b.Header()); err != nil { return fmt.Errorf("Imported block header validation failed: %v", err) } } return nil }
// add validates a transaction and inserts it into the non-executable queue for // later pending promotion and execution. func (pool *TxPool) add(tx *types.Transaction) error { // If the transaction is alreayd known, discard it hash := tx.Hash() if pool.all[hash] != nil { return fmt.Errorf("Known transaction: %x", hash[:4]) } // Otherwise ensure basic validation passes and queue it up if err := pool.validateTx(tx); err != nil { return err } pool.enqueueTx(hash, tx) // Print a log message if low enough level is set if glog.V(logger.Debug) { rcpt := "[NEW_CONTRACT]" if to := tx.To(); to != nil { rcpt = common.Bytes2Hex(to[:4]) } from, _ := tx.From() // from already verified during tx validation glog.Infof("(t) 0x%x => %s (%v) %x\n", from[:4], rcpt, tx.Value, hash) } return nil }
// ReportBlock reports the block to the block reporting tool found at // badblocks.ethdev.com func ReportBlock(block *types.Block, err error) { if DisableBadBlockReporting { return } const url = "https://badblocks.ethdev.com" blockRlp, _ := rlp.EncodeToBytes(block) data := map[string]interface{}{ "block": common.Bytes2Hex(blockRlp), "errortype": err.Error(), "hints": map[string]interface{}{ "receipts": "NYI", "vmtrace": "NYI", }, } jsonStr, _ := json.Marshal(map[string]interface{}{"method": "eth_badBlock", "params": []interface{}{data}, "id": "1", "jsonrpc": "2.0"}) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { glog.V(logger.Error).Infoln("POST err:", err) return } defer resp.Body.Close() if glog.V(logger.Debug) { glog.Infoln("response Status:", resp.Status) glog.Infoln("response Headers:", resp.Header) body, _ := ioutil.ReadAll(resp.Body) glog.Infoln("response Body:", string(body)) } }
func (k *KeyPair) Mnemonic() string { if k.mnemonic == "" { k.mnemonic = strings.Join(MnemonicEncode(common.Bytes2Hex(k.PrivateKey)), " ") } return k.mnemonic }
func (d *hexdata) String() string { return "0x" + common.Bytes2Hex(d.data) }
func (k *KeyPair) AsStrings() (string, string, string, string) { return k.Mnemonic(), common.Bytes2Hex(k.Address()), common.Bytes2Hex(k.PrivateKey), common.Bytes2Hex(k.PublicKey) }