Exemplo n.º 1
0
func NewReciept(contractCreation bool, creationAddress, hash, address []byte) *Receipt {
	return &Receipt{
		contractCreation,
		common.ToHex(creationAddress),
		common.ToHex(hash),
		common.ToHex(address),
	}
}
Exemplo n.º 2
0
// NewWhisperMessage converts an internal message into an API version.
func NewWhisperMessage(message *Message) WhisperMessage {
	return WhisperMessage{
		ref: message,

		Payload: common.ToHex(message.Payload),
		From:    common.ToHex(crypto.FromECDSAPub(message.Recover())),
		To:      common.ToHex(crypto.FromECDSAPub(message.To)),
		Sent:    message.Sent.Unix(),
		TTL:     int64(message.TTL / time.Second),
		Hash:    common.ToHex(message.Hash.Bytes()),
	}
}
Exemplo n.º 3
0
func (self *Object) Storage() (storage map[string]string) {
	storage = make(map[string]string)

	it := self.StateObject.Trie().Iterator()
	for it.Next() {
		var data []byte
		rlp.Decode(bytes.NewReader(it.Value), &data)
		storage[common.ToHex(self.Trie().GetKey(it.Key))] = common.ToHex(data)
	}

	return
}
Exemplo n.º 4
0
func (self *XEth) EachStorage(addr string) string {
	var values []KeyVal
	object := self.State().SafeGet(addr)
	it := object.Trie().Iterator()
	for it.Next() {
		values = append(values, KeyVal{common.ToHex(object.Trie().GetKey(it.Key)), common.ToHex(it.Value)})
	}

	valuesJson, err := json.Marshal(values)
	if err != nil {
		return ""
	}

	return string(valuesJson)
}
Exemplo n.º 5
0
func NewTx(tx *types.Transaction) *Transaction {
	sender, err := tx.From()
	if err != nil {
		return nil
	}
	hash := tx.Hash().Hex()

	var receiver string
	if to := tx.To(); to != nil {
		receiver = to.Hex()
	} else {
		from, _ := tx.From()
		receiver = crypto.CreateAddress(from, tx.Nonce()).Hex()
	}
	createsContract := core.MessageCreatesContract(tx)

	var data string
	if createsContract {
		data = strings.Join(core.Disassemble(tx.Data()), "\n")
	} else {
		data = common.ToHex(tx.Data())
	}

	return &Transaction{ref: tx, Hash: hash, Value: common.CurrencyToString(tx.Value()), Address: receiver, Contract: createsContract, Gas: tx.Gas().String(), GasPrice: tx.GasPrice().String(), Data: data, Sender: sender.Hex(), CreatesContract: createsContract, RawData: common.ToHex(tx.Data())}
}
Exemplo n.º 6
0
// Creates a new QML Block from a chain block
func NewBlock(block *types.Block) *Block {
	if block == nil {
		return &Block{}
	}

	ptxs := make([]*Transaction, len(block.Transactions()))
	/*
		for i, tx := range block.Transactions() {
			ptxs[i] = NewTx(tx)
		}
	*/
	txlist := common.NewList(ptxs)

	puncles := make([]*Block, len(block.Uncles()))
	/*
		for i, uncle := range block.Uncles() {
			puncles[i] = NewBlock(types.NewBlockWithHeader(uncle))
		}
	*/
	ulist := common.NewList(puncles)

	return &Block{
		ref: block, Size: block.Size().String(),
		Number: int(block.NumberU64()), GasUsed: block.GasUsed().String(),
		GasLimit: block.GasLimit().String(), Hash: block.Hash().Hex(),
		Transactions: txlist, Uncles: ulist,
		Time:     block.Time(),
		Coinbase: block.Coinbase().Hex(),
		PrevHash: block.ParentHash().Hex(),
		Bloom:    common.ToHex(block.Bloom().Bytes()),
		Raw:      block.String(),
	}
}
Exemplo n.º 7
0
// ContractCall implements ContractCaller.ContractCall, delegating the execution of
// a contract call to the remote node, returning the reply to for local processing.
func (b *rpcBackend) ContractCall(contract common.Address, data []byte, pending bool) ([]byte, error) {
	// Pack up the request into an RPC argument
	args := struct {
		To   common.Address `json:"to"`
		Data string         `json:"data"`
	}{
		To:   contract,
		Data: common.ToHex(data),
	}
	// Execute the RPC call and retrieve the response
	block := "latest"
	if pending {
		block = "pending"
	}
	res, err := b.request("exp_call", []interface{}{args, block})
	if err != nil {
		return nil, err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return nil, err
	}
	// Convert the response back to a Go byte slice and return
	return common.FromHex(hex), nil
}
Exemplo n.º 8
0
// EstimateGasLimit implements ContractTransactor.EstimateGasLimit, delegating
// the gas estimation to the remote node.
func (b *rpcBackend) EstimateGasLimit(sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
	// Pack up the request into an RPC argument
	args := struct {
		From  common.Address  `json:"from"`
		To    *common.Address `json:"to"`
		Value *rpc.HexNumber  `json:"value"`
		Data  string          `json:"data"`
	}{
		From:  sender,
		To:    contract,
		Data:  common.ToHex(data),
		Value: rpc.NewHexNumber(value),
	}
	// Execute the RPC call and retrieve the response
	res, err := b.request("exp_estimateGas", []interface{}{args})
	if err != nil {
		return nil, err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return nil, err
	}
	estimate, ok := new(big.Int).SetString(hex, 0)
	if !ok {
		return nil, fmt.Errorf("invalid estimate hex: %s", hex)
	}
	return estimate, nil
}
Exemplo n.º 9
0
// NewIdentity generates a new cryptographic identity for the client, and injects
// it into the known identities for message decryption.
func (s *PublicWhisperAPI) NewIdentity() (string, error) {
	if s.w == nil {
		return "", whisperOffLineErr
	}

	identity := s.w.NewIdentity()
	return common.ToHex(crypto.FromECDSAPub(&identity.PublicKey)), nil
}
Exemplo n.º 10
0
// Calculates the sha3 over req.Params.Data
func (self *web3Api) Sha3(req *shared.Request) (interface{}, error) {
	args := new(Sha3Args)
	if err := self.codec.Decode(req.Params, &args); err != nil {
		return nil, err
	}

	return common.ToHex(crypto.Sha3(common.FromHex(args.Data))), nil
}
Exemplo n.º 11
0
// EstimateGasLimit implements bind.ContractTransactor triing to estimate the gas
// needed to execute a specific transaction based on the current pending state of
// the backend blockchain. There is no guarantee that this is the true gas limit
// requirement as other transactions may be added or removed by miners, but it
// should provide a basis for setting a reasonable default.
func (b *ContractBackend) EstimateGasLimit(sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
	out, err := b.bcapi.EstimateGas(CallArgs{
		From:  sender,
		To:    contract,
		Value: *rpc.NewHexNumber(value),
		Data:  common.ToHex(data),
	})
	return out.BigInt(), err
}
Exemplo n.º 12
0
func (self *testBackend) initUrlHint() {
	self.contracts[UrlHintAddr[2:]] = make(map[string]string)
	mapaddr := storageMapping(storageIdx2Addr(1), hash[:])

	key := storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(0)))
	self.contracts[UrlHintAddr[2:]][key] = common.ToHex([]byte(url))
	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(1)))
	self.contracts[UrlHintAddr[2:]][key] = "0x0"
}
Exemplo n.º 13
0
func (self *XEth) Sign(fromStr, hashStr string, didUnlock bool) (string, error) {
	var (
		from = common.HexToAddress(fromStr)
		hash = common.HexToHash(hashStr)
	)
	sig, err := self.doSign(from, hash, didUnlock)
	if err != nil {
		return "", err
	}
	return common.ToHex(sig), nil
}
Exemplo n.º 14
0
// ContractCall implements bind.ContractCaller executing an Ethereum contract
// call with the specified data as the input. The pending flag requests execution
// against the pending block, not the stable head of the chain.
func (b *ContractBackend) ContractCall(contract common.Address, data []byte, pending bool) ([]byte, error) {
	// Convert the input args to the API spec
	args := CallArgs{
		To:   &contract,
		Data: common.ToHex(data),
	}
	block := rpc.LatestBlockNumber
	if pending {
		block = rpc.PendingBlockNumber
	}
	// Execute the call and convert the output back to Go types
	out, err := b.bcapi.Call(args, block)
	return common.FromHex(out), err
}
Exemplo n.º 15
0
// SendTransaction implements ContractTransactor.SendTransaction, delegating the
// raw transaction injection to the remote node.
func (b *rpcBackend) SendTransaction(tx *types.Transaction) error {
	data, err := rlp.EncodeToBytes(tx)
	if err != nil {
		return err
	}
	res, err := b.request("exp_sendRawTransaction", []interface{}{common.ToHex(data)})
	if err != nil {
		return err
	}
	var hex string
	if err := json.Unmarshal(res, &hex); err != nil {
		return err
	}
	return nil
}
Exemplo n.º 16
0
func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, string, error) {
	statedb := self.State().State().Copy()
	var from *state.StateObject
	if len(fromStr) == 0 {
		accounts, err := self.backend.AccountManager().Accounts()
		if err != nil || len(accounts) == 0 {
			from = statedb.GetOrNewStateObject(common.Address{})
		} else {
			from = statedb.GetOrNewStateObject(accounts[0].Address)
		}
	} else {
		from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr))
	}

	from.SetBalance(common.MaxBig)
	from.SetGasLimit(common.MaxBig)

	msg := callmsg{
		from:     from,
		gas:      common.Big(gasStr),
		gasPrice: common.Big(gasPriceStr),
		value:    common.Big(valueStr),
		data:     common.FromHex(dataStr),
	}
	if len(toStr) > 0 {
		addr := common.HexToAddress(toStr)
		msg.to = &addr
	}

	if msg.gas.Cmp(big.NewInt(0)) == 0 {
		msg.gas = big.NewInt(50000000)
	}

	if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
		msg.gasPrice = self.DefaultGasPrice()
	}

	header := self.CurrentBlock().Header()
	vmenv := core.NewEnv(statedb, self.backend.ChainManager(), msg, header)

	res, gas, err := core.ApplyMessage(vmenv, msg, from)
	return common.ToHex(res), gas.String(), err
}
Exemplo n.º 17
0
func NewTestBackend() *testBackend {
	HashRegAddr = common.BigToAddress(common.Big0).Hex() //[2:]
	UrlHintAddr = common.BigToAddress(common.Big1).Hex() //[2:]
	self := &testBackend{}
	self.contracts = make(map[string](map[string]string))

	self.contracts[HashRegAddr[2:]] = make(map[string]string)
	key := storageAddress(storageMapping(storageIdx2Addr(1), codehash[:]))
	self.contracts[HashRegAddr[2:]][key] = hash.Hex()

	self.contracts[UrlHintAddr[2:]] = make(map[string]string)
	mapaddr := storageMapping(storageIdx2Addr(1), hash[:])

	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(0)))
	self.contracts[UrlHintAddr[2:]][key] = common.ToHex([]byte(url))
	key = storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(1)))
	self.contracts[UrlHintAddr[2:]][key] = "0x0"
	return self
}
Exemplo n.º 18
0
func abiSignature(s string) string {
	return common.ToHex(crypto.Keccak256([]byte(s))[:4])
}
Exemplo n.º 19
0
// Sha3 applies the expanse sha3 implementation on the input.
// It assumes the input is hex encoded.
func (s *PublicWeb3API) Sha3(input string) string {
	return common.ToHex(crypto.Keccak256(common.FromHex(input)))
}
Exemplo n.º 20
0
func abiSignature(s string) string {
	return common.ToHex(crypto.Sha3([]byte(s))[:4])
}
Exemplo n.º 21
0
func (self *XEth) BalanceAt(addr string) string {
	return common.ToHex(self.State().state.GetBalance(common.HexToAddress(addr)).Bytes())
}
Exemplo n.º 22
0
func (self *XEth) CodeAt(address string) string {
	return common.ToHex(self.State().state.GetCode(common.HexToAddress(address)))
}
Exemplo n.º 23
0
func storageAddress(addr []byte) string {
	return common.ToHex(addr)
}
Exemplo n.º 24
0
func (self *XEth) ToAscii(str string) string {
	padded := common.RightPadBytes([]byte(str), 32)

	return "0x" + common.ToHex(padded)
}
Exemplo n.º 25
0
// NewIdentity generates a new cryptographic identity for the client, and injects
// it into the known identities for message decryption.
func (self *Whisper) NewIdentity() string {
	identity := self.Whisper.NewIdentity()
	return common.ToHex(crypto.FromECDSAPub(&identity.PublicKey))
}
Exemplo n.º 26
0
func MakeTargetHex(minerDifficulty float64) string {
	minerAdjustedDifficulty := int64(minerDifficulty * 1000000 * 100)
	difficulty := big.NewInt(minerAdjustedDifficulty)
	diff1 := new(big.Int).Div(pow256, difficulty)
	return string(common.ToHex(diff1.Bytes()))
}
Exemplo n.º 27
0
// SendTransaction implements bind.ContractTransactor injects the transaction
// into the pending pool for execution.
func (b *ContractBackend) SendTransaction(tx *types.Transaction) error {
	raw, _ := rlp.EncodeToBytes(tx)
	_, err := b.txapi.SendRawTransaction(common.ToHex(raw))
	return err
}
Exemplo n.º 28
0
func TestContract(t *testing.T) {
	t.Skip("contract testing is implemented with mining in ethash test mode. This takes about 7seconds to run. Unskip and run on demand")
	coinbase := common.HexToAddress(testAddress)
	tmp, repl, expanse := testREPL(t, func(conf *exp.Config) {
		conf.Etherbase = coinbase
		conf.PowTest = true
	})
	if err := expanse.Start(); err != nil {
		t.Errorf("error starting expanse: %v", err)
		return
	}
	defer expanse.Stop()
	defer os.RemoveAll(tmp)

	reg := registrar.New(repl.xeth)
	_, err := reg.SetGlobalRegistrar("", coinbase)
	if err != nil {
		t.Errorf("error setting HashReg: %v", err)
	}
	_, err = reg.SetHashReg("", coinbase)
	if err != nil {
		t.Errorf("error setting HashReg: %v", err)
	}
	_, err = reg.SetUrlHint("", coinbase)
	if err != nil {
		t.Errorf("error setting HashReg: %v", err)
	}
	/* TODO:
	* lookup receipt and contract addresses by tx hash
	* name registration for HashReg and UrlHint addresses
	* mine those transactions
	* then set once more SetHashReg SetUrlHint
	 */

	source := `contract test {\n` +
		"   /// @notice Will multiply `a` by 7." + `\n` +
		`   function multiply(uint a) returns(uint d) {\n` +
		`       return a * 7;\n` +
		`   }\n` +
		`}\n`

	if checkEvalJSON(t, repl, `admin.stopNatSpec()`, `true`) != nil {
		return
	}

	contractInfo, err := ioutil.ReadFile("info_test.json")
	if err != nil {
		t.Fatalf("%v", err)
	}
	if checkEvalJSON(t, repl, `primary = exp.accounts[0]`, `"`+testAddress+`"`) != nil {
		return
	}
	if checkEvalJSON(t, repl, `source = "`+source+`"`, `"`+source+`"`) != nil {
		return
	}

	// if solc is found with right version, test it, otherwise read from file
	sol, err := compiler.New("")
	if err != nil {
		t.Logf("solc not found: mocking contract compilation step")
	} else if sol.Version() != solcVersion {
		t.Logf("WARNING: solc different version found (%v, test written for %v, may need to update)", sol.Version(), solcVersion)
	}

	if err != nil {
		info, err := ioutil.ReadFile("info_test.json")
		if err != nil {
			t.Fatalf("%v", err)
		}
		_, err = repl.re.Run(`contract = JSON.parse(` + strconv.Quote(string(info)) + `)`)
		if err != nil {
			t.Errorf("%v", err)
		}
	} else {
		if checkEvalJSON(t, repl, `contract = exp.compile.solidity(source).test`, string(contractInfo)) != nil {
			return
		}
	}

	if checkEvalJSON(t, repl, `contract.code`, `"0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056"`) != nil {
		return
	}

	if checkEvalJSON(
		t, repl,
		`contractaddress = exp.sendTransaction({from: primary, data: contract.code})`,
		`"0x46d69d55c3c4b86a924a92c9fc4720bb7bce1d74"`,
	) != nil {
		return
	}

	if !processTxs(repl, t, 8) {
		return
	}

	callSetup := `abiDef = JSON.parse('[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]');
Multiply7 = exp.contract(abiDef);
multiply7 = Multiply7.at(contractaddress);
`
	_, err = repl.re.Run(callSetup)
	if err != nil {
		t.Errorf("unexpected error setting up contract, got %v", err)
		return
	}

	expNotice := ""
	if repl.lastConfirm != expNotice {
		t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
		return
	}

	if checkEvalJSON(t, repl, `admin.startNatSpec()`, `true`) != nil {
		return
	}
	if checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary })`, `"0x4ef9088431a8033e4580d00e4eb2487275e031ff4163c7529df0ef45af17857b"`) != nil {
		return
	}

	if !processTxs(repl, t, 1) {
		return
	}

	expNotice = `About to submit transaction (no NatSpec info found for contract: content hash not found for '0x87e2802265838c7f14bb69eecd2112911af6767907a702eeaa445239fb20711b'): {"params":[{"to":"0x46d69d55c3c4b86a924a92c9fc4720bb7bce1d74","data": "0xc6888fa10000000000000000000000000000000000000000000000000000000000000006"}]}`
	if repl.lastConfirm != expNotice {
		t.Errorf("incorrect confirmation message: expected\n%v, got\n%v", expNotice, repl.lastConfirm)
		return
	}

	var contentHash = `"0x86d2b7cf1e72e9a7a3f8d96601f0151742a2f780f1526414304fbe413dc7f9bd"`
	if sol != nil && solcVersion != sol.Version() {
		modContractInfo := versionRE.ReplaceAll(contractInfo, []byte(`"compilerVersion":"`+sol.Version()+`"`))
		fmt.Printf("modified contractinfo:\n%s\n", modContractInfo)
		contentHash = `"` + common.ToHex(crypto.Sha3([]byte(modContractInfo))) + `"`
	}
	if checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`) != nil {
		return
	}
	if checkEvalJSON(t, repl, `contentHash = admin.saveInfo(contract.info, filename)`, contentHash) != nil {
		return
	}
	if checkEvalJSON(t, repl, `admin.register(primary, contractaddress, contentHash)`, `true`) != nil {
		return
	}
	if checkEvalJSON(t, repl, `admin.registerUrl(primary, contentHash, "file://"+filename)`, `true`) != nil {
		return
	}

	if checkEvalJSON(t, repl, `admin.startNatSpec()`, `true`) != nil {
		return
	}

	if !processTxs(repl, t, 3) {
		return
	}

	if checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary })`, `"0x66d7635c12ad0b231e66da2f987ca3dfdca58ffe49c6442aa55960858103fd0c"`) != nil {
		return
	}

	if !processTxs(repl, t, 1) {
		return
	}

	expNotice = "Will multiply 6 by 7."
	if repl.lastConfirm != expNotice {
		t.Errorf("incorrect confirmation message: expected\n%v, got\n%v", expNotice, repl.lastConfirm)
		return
	}
}