Example #1
0
func (self *JSRE) mainLoop() {
	// Subscribe to events
	reactor := self.ethereum.Reactor()
	reactor.Subscribe("newBlock", self.blockChan)

out:
	for {
		select {
		case <-self.quitChan:
			break out
		case block := <-self.blockChan:
			if _, ok := block.Resource.(*ethchain.Block); ok {
			}
		case object := <-self.changeChan:
			if stateObject, ok := object.Resource.(*ethchain.StateObject); ok {
				for _, cb := range self.objectCb[ethutil.Bytes2Hex(stateObject.Address())] {
					val, _ := self.vm.ToValue(ethpub.NewPStateObject(stateObject))
					cb.Call(cb, val)
				}
			} else if storageObject, ok := object.Resource.(*ethchain.StorageState); ok {
				for _, cb := range self.objectCb[ethutil.Bytes2Hex(storageObject.StateAddress)+ethutil.Bytes2Hex(storageObject.Address)] {
					val, _ := self.vm.ToValue(ethpub.NewPStorageState(storageObject))
					cb.Call(cb, val)
				}
			}
		}
	}
}
Example #2
0
func (self *State) Dump() []byte {
	world := World{
		Root:     ethutil.Bytes2Hex(self.Trie.Root.([]byte)),
		Accounts: make(map[string]Account),
	}

	self.Trie.NewIterator().Each(func(key string, value *ethutil.Value) {
		stateObject := NewStateObjectFromBytes([]byte(key), value.Bytes())

		account := Account{Balance: stateObject.Balance.String(), Nonce: stateObject.Nonce, CodeHash: ethutil.Bytes2Hex(stateObject.CodeHash)}
		account.Storage = make(map[string]string)

		stateObject.EachStorage(func(key string, value *ethutil.Value) {
			value.Decode()
			account.Storage[ethutil.Bytes2Hex([]byte(key))] = ethutil.Bytes2Hex(value.Bytes())
		})
		world.Accounts[ethutil.Bytes2Hex([]byte(key))] = account
	})

	json, err := json.MarshalIndent(world, "", "    ")
	if err != nil {
		fmt.Println("dump err", err)
	}

	return json
}
Example #3
0
func NewJSReciept(contractCreation bool, creationAddress, hash, address []byte) *JSReceipt {
	return &JSReceipt{
		contractCreation,
		ethutil.Bytes2Hex(creationAddress),
		ethutil.Bytes2Hex(hash),
		ethutil.Bytes2Hex(address),
	}
}
Example #4
0
func (gui *Gui) Transact(recipient, value, gas, gasPrice, d string) (*ethpipe.JSReceipt, error) {
	var data string
	if len(recipient) == 0 {
		code, err := ethutil.Compile(d, false)
		if err != nil {
			return nil, err
		}
		data = ethutil.Bytes2Hex(code)
	} else {
		data = ethutil.Bytes2Hex(utils.FormatTransactionData(d))
	}

	return gui.pipe.Transact(gui.privateKey(), recipient, value, gas, gasPrice, data)
}
Example #5
0
func (self *JSPipe) EachStorage(addr string) string {
	var values []KeyVal
	object := self.World().SafeGet(ethutil.Hex2Bytes(addr))
	object.EachStorage(func(name string, value *ethutil.Value) {
		value.Decode()
		values = append(values, KeyVal{ethutil.Bytes2Hex([]byte(name)), ethutil.Bytes2Hex(value.Bytes())})
	})

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

	return string(valuesJson)
}
Example #6
0
// Validates the current block. Returns an error if the block was invalid,
// an uncle or anything that isn't on the current block chain.
// Validation validates easy over difficult (dagger takes longer time = difficult)
func (sm *StateManager) ValidateBlock(block *Block) error {
	// TODO
	// 2. Check if the difficulty is correct

	// Check each uncle's previous hash. In order for it to be valid
	// is if it has the same block hash as the current
	previousBlock := sm.bc.GetBlock(block.PrevHash)
	for _, uncle := range block.Uncles {
		if bytes.Compare(uncle.PrevHash, previousBlock.PrevHash) != 0 {
			return ValidationError("Mismatch uncle's previous hash. Expected %x, got %x", previousBlock.PrevHash, uncle.PrevHash)
		}
	}

	diff := block.Time - previousBlock.Time
	if diff < 0 {
		return ValidationError("Block timestamp less then prev block %v (%v - %v)", diff, block.Time, sm.bc.CurrentBlock.Time)
	}

	/* XXX
	// New blocks must be within the 15 minute range of the last block.
	if diff > int64(15*time.Minute) {
		return ValidationError("Block is too far in the future of last block (> 15 minutes)")
	}
	*/

	// Verify the nonce of the block. Return an error if it's not valid
	if !sm.Pow.Verify(block.HashNoNonce(), block.Difficulty, block.Nonce) {
		return ValidationError("Block's nonce is invalid (= %v)", ethutil.Bytes2Hex(block.Nonce))
	}

	return nil
}
Example #7
0
func (self *JSPipe) SecretToAddress(key string) string {
	pair, err := ethcrypto.NewKeyPairFromSec(ethutil.Hex2Bytes(key))
	if err != nil {
		return ""
	}

	return ethutil.Bytes2Hex(pair.Address())
}
Example #8
0
func (self *JSPipe) CompileMutan(code string) string {
	data, err := self.Pipe.CompileMutan(code)
	if err != nil {
		return err.Error()
	}

	return ethutil.Bytes2Hex(data)
}
Example #9
0
func (k *FileKeyStore) Save(session string, keyRing *KeyRing) error {
	var content []byte
	var err error
	var privateKeys []string
	var publicKeys []string
	var mnemonics []string
	var addresses []string
	keyRing.Each(func(keyPair *KeyPair) {
		privateKeys = append(privateKeys, ethutil.Bytes2Hex(keyPair.PrivateKey))
		publicKeys = append(publicKeys, ethutil.Bytes2Hex(keyPair.PublicKey))
		addresses = append(addresses, ethutil.Bytes2Hex(keyPair.Address()))
		mnemonics = append(mnemonics, keyPair.Mnemonic())
	})

	basename := session
	if session == "" {
		basename = "default"
	}

	path := path.Join(k.basedir, basename)
	content = []byte(strings.Join(privateKeys, "\n"))
	err = ioutil.WriteFile(path+".prv", content, 0600)
	if err != nil {
		return err
	}

	content = []byte(strings.Join(publicKeys, "\n"))
	err = ioutil.WriteFile(path+".pub", content, 0644)
	if err != nil {
		return err
	}

	content = []byte(strings.Join(addresses, "\n"))
	err = ioutil.WriteFile(path+".addr", content, 0644)
	if err != nil {
		return err
	}

	content = []byte(strings.Join(mnemonics, "\n"))
	err = ioutil.WriteFile(path+".mne", content, 0600)
	if err != nil {
		return err
	}

	return nil
}
Example #10
0
func (gui *Gui) insertTransaction(window string, tx *ethchain.Transaction) {
	nameReg := ethpipe.New(gui.eth).World().Config().Get("NameReg")
	addr := gui.address()

	var inout string
	if bytes.Compare(tx.Sender(), addr) == 0 {
		inout = "send"
	} else {
		inout = "recv"
	}

	var (
		ptx  = ethpipe.NewJSTx(tx)
		send = nameReg.Storage(tx.Sender())
		rec  = nameReg.Storage(tx.Recipient)
		s, r string
	)

	if tx.CreatesContract() {
		rec = nameReg.Storage(tx.CreationAddress())
	}

	if send.Len() != 0 {
		s = strings.Trim(send.Str(), "\x00")
	} else {
		s = ethutil.Bytes2Hex(tx.Sender())
	}
	if rec.Len() != 0 {
		r = strings.Trim(rec.Str(), "\x00")
	} else {
		if tx.CreatesContract() {
			r = ethutil.Bytes2Hex(tx.CreationAddress())
		} else {
			r = ethutil.Bytes2Hex(tx.Recipient)
		}
	}
	ptx.Sender = s
	ptx.Address = r

	if window == "post" {
		gui.getObjectByName("transactionView").Call("addTx", ptx, inout)
	} else {
		gui.getObjectByName("pendingTxView").Call("addTx", ptx, inout)
	}
}
Example #11
0
func NewJSTx(tx *ethchain.Transaction) *JSTransaction {
	hash := ethutil.Bytes2Hex(tx.Hash())
	receiver := ethutil.Bytes2Hex(tx.Recipient)
	if receiver == "0000000000000000000000000000000000000000" {
		receiver = ethutil.Bytes2Hex(tx.CreationAddress())
	}
	sender := ethutil.Bytes2Hex(tx.Sender())
	createsContract := tx.CreatesContract()

	var data string
	if tx.CreatesContract() {
		data = strings.Join(ethchain.Disassemble(tx.Data), "\n")
	} else {
		data = ethutil.Bytes2Hex(tx.Data)
	}

	return &JSTransaction{ref: tx, Hash: hash, Value: ethutil.CurrencyToString(tx.Value), Address: receiver, Contract: tx.CreatesContract(), Gas: tx.Gas.String(), GasPrice: tx.GasPrice.String(), Data: data, Sender: sender, CreatesContract: createsContract, RawData: ethutil.Bytes2Hex(tx.Data)}
}
Example #12
0
func (self *JSStateObject) EachStorage(call otto.FunctionCall) otto.Value {
	cb := call.Argument(0)
	self.JSObject.EachStorage(func(key string, value *ethutil.Value) {
		value.Decode()

		cb.Call(self.eth.toVal(self), self.eth.toVal(key), self.eth.toVal(ethutil.Bytes2Hex(value.Bytes())))
	})

	return otto.UndefinedValue()
}
Example #13
0
func (self *UiLib) StartDbWithContractAndData(contractHash, data string) {
	dbWindow := NewDebuggerWindow(self)
	object := self.eth.StateManager().CurrentState().GetStateObject(ethutil.Hex2Bytes(contractHash))
	if len(object.Code) > 0 {
		dbWindow.SetCode("0x" + ethutil.Bytes2Hex(object.Code))
	}
	dbWindow.SetData("0x" + data)

	dbWindow.Show()
}
Example #14
0
func (gui *Gui) loadAddressBook() {
	gui.win.Root().Call("clearAddress")

	nameReg := ethpub.EthereumConfig(gui.eth.StateManager()).NameReg()
	if nameReg != nil {
		nameReg.State().EachStorage(func(name string, value *ethutil.Value) {
			if name[0] != 0 {
				gui.win.Root().Call("addAddress", struct{ Name, Address string }{name, ethutil.Bytes2Hex(value.Bytes())})
			}
		})
	}
}
Example #15
0
func (gui *Gui) loadAddressBook() {
	view := gui.getObjectByName("infoView")
	view.Call("clearAddress")

	nameReg := gui.pipe.World().Config().Get("NameReg")
	if nameReg != nil {
		nameReg.EachStorage(func(name string, value *ethutil.Value) {
			if name[0] != 0 {
				value.Decode()

				view.Call("addAddress", struct{ Name, Address string }{name, ethutil.Bytes2Hex(value.Bytes())})
			}
		})
	}
}
Example #16
0
func NewJSMessage(message *ethstate.Message) JSMessage {
	return JSMessage{
		To:        ethutil.Bytes2Hex(message.To),
		From:      ethutil.Bytes2Hex(message.From),
		Input:     ethutil.Bytes2Hex(message.Input),
		Output:    ethutil.Bytes2Hex(message.Output),
		Path:      message.Path,
		Origin:    ethutil.Bytes2Hex(message.Origin),
		Timestamp: int32(message.Timestamp),
		Coinbase:  ethutil.Bytes2Hex(message.Origin),
		Block:     ethutil.Bytes2Hex(message.Block),
		Number:    int32(message.Number.Int64()),
	}
}
Example #17
0
func (self *UiLib) Transact(object map[string]interface{}) (*ethpipe.JSReceipt, error) {
	// Default values
	if object["from"] == nil {
		object["from"] = ""
	}
	if object["to"] == nil {
		object["to"] = ""
	}
	if object["value"] == nil {
		object["value"] = ""
	}
	if object["gas"] == nil {
		object["gas"] = ""
	}
	if object["gasPrice"] == nil {
		object["gasPrice"] = ""
	}

	var dataStr string
	var data []string
	if list, ok := object["data"].(*qml.List); ok {
		list.Convert(&data)
	}

	for _, str := range data {
		if ethutil.IsHex(str) {
			str = str[2:]

			if len(str) != 64 {
				str = ethutil.LeftPadString(str, 64)
			}
		} else {
			str = ethutil.Bytes2Hex(ethutil.LeftPadBytes(ethutil.Big(str).Bytes(), 32))
		}

		dataStr += str
	}

	return self.JSPipe.Transact(
		object["from"].(string),
		object["to"].(string),
		object["value"].(string),
		object["gas"].(string),
		object["gasPrice"].(string),
		dataStr,
	)
}
Example #18
0
func (p *EthereumApi) GetStorageAt(args *GetStorageArgs, reply *string) error {
	err := args.requirements()
	if err != nil {
		return err
	}

	state := p.pipe.World().SafeGet(ethutil.Hex2Bytes(args.Address))

	var hx string
	if strings.Index(args.Key, "0x") == 0 {
		hx = string([]byte(args.Key)[2:])
	} else {
		// Convert the incoming string (which is a bigint) into hex
		i, _ := new(big.Int).SetString(args.Key, 10)
		hx = ethutil.Bytes2Hex(i.Bytes())
	}
	logger.Debugf("GetStorageAt(%s, %s)\n", args.Address, hx)
	value := state.Storage(ethutil.Hex2Bytes(hx))
	*reply = NewSuccessRes(GetStorageAtRes{Address: args.Address, Key: args.Key, Value: value.Str()})
	return nil
}
Example #19
0
func (self *JSPipe) CoinBase() string {
	return ethutil.Bytes2Hex(self.obj.KeyManager().Address())
}
Example #20
0
func NewJSKey(key *ethcrypto.KeyPair) *JSKey {
	return &JSKey{ethutil.Bytes2Hex(key.Address()), ethutil.Bytes2Hex(key.PrivateKey), ethutil.Bytes2Hex(key.PublicKey)}
}
Example #21
0
func (self *JSPipe) ToAscii(str string) string {
	padded := ethutil.RightPadBytes([]byte(str), 32)

	return "0x" + ethutil.Bytes2Hex(padded)
}
Example #22
0
// Creates a new QML Block from a chain block
func NewJSBlock(block *ethchain.Block) *JSBlock {
	if block == nil {
		return nil
	}

	var ptxs []JSTransaction
	for _, tx := range block.Transactions() {
		ptxs = append(ptxs, *NewJSTx(tx))
	}

	txJson, err := json.Marshal(ptxs)
	if err != nil {
		return nil
	}

	return &JSBlock{ref: block, Number: int(block.Number.Uint64()), GasUsed: block.GasUsed.String(), GasLimit: block.GasLimit.String(), Hash: ethutil.Bytes2Hex(block.Hash()), Transactions: string(txJson), Time: block.Time, Coinbase: ethutil.Bytes2Hex(block.Coinbase)}
}
Example #23
0
func (k *KeyPair) Mnemonic() string {
	if k.mnemonic == "" {
		k.mnemonic = strings.Join(MnemonicEncode(ethutil.Bytes2Hex(k.PrivateKey)), " ")
	}
	return k.mnemonic
}
func (app *HtmlApplication) NewBlock(block *ethchain.Block) {
	b := &ethpipe.JSBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Bytes2Hex(block.Hash())}
	app.webView.Call("onNewBlockCb", b)
}
Example #25
0
func (k *KeyPair) AsStrings() (string, string, string, string) {
	return k.Mnemonic(), ethutil.Bytes2Hex(k.Address()), ethutil.Bytes2Hex(k.PrivateKey), ethutil.Bytes2Hex(k.PublicKey)
}
Example #26
0
func (gui *Gui) privateKey() string {
	return ethutil.Bytes2Hex(gui.eth.KeyManager().PrivateKey())
}
Example #27
0
// Events
func (app *QmlApplication) NewBlock(block *ethchain.Block) {
	pblock := &ethpub.PBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Bytes2Hex(block.Hash())}
	app.win.Call("onNewBlockCb", pblock)
}