forked from mirror/go-ethereum
commit
2096b3a9ed
@ -1,76 +0,0 @@ |
||||
package ethchain |
||||
|
||||
import ( |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
"math/big" |
||||
) |
||||
|
||||
type Account struct { |
||||
address []byte |
||||
Amount *big.Int |
||||
Nonce uint64 |
||||
} |
||||
|
||||
func NewAccount(address []byte, amount *big.Int) *Account { |
||||
return &Account{address, amount, 0} |
||||
} |
||||
|
||||
func NewAccountFromData(address, data []byte) *Account { |
||||
account := &Account{address: address} |
||||
account.RlpDecode(data) |
||||
|
||||
return account |
||||
} |
||||
|
||||
func (a *Account) AddFee(fee *big.Int) { |
||||
a.AddFunds(fee) |
||||
} |
||||
|
||||
func (a *Account) AddFunds(funds *big.Int) { |
||||
a.Amount.Add(a.Amount, funds) |
||||
} |
||||
|
||||
func (a *Account) Address() []byte { |
||||
return a.address |
||||
} |
||||
|
||||
// Implements Callee
|
||||
func (a *Account) ReturnGas(value *big.Int, state *State) { |
||||
// Return the value back to the sender
|
||||
a.AddFunds(value) |
||||
state.UpdateAccount(a.address, a) |
||||
} |
||||
|
||||
func (a *Account) RlpEncode() []byte { |
||||
return ethutil.Encode([]interface{}{a.Amount, a.Nonce}) |
||||
} |
||||
|
||||
func (a *Account) RlpDecode(data []byte) { |
||||
decoder := ethutil.NewValueFromBytes(data) |
||||
|
||||
a.Amount = decoder.Get(0).BigInt() |
||||
a.Nonce = decoder.Get(1).Uint() |
||||
} |
||||
|
||||
type AddrStateStore struct { |
||||
states map[string]*AccountState |
||||
} |
||||
|
||||
func NewAddrStateStore() *AddrStateStore { |
||||
return &AddrStateStore{states: make(map[string]*AccountState)} |
||||
} |
||||
|
||||
func (s *AddrStateStore) Add(addr []byte, account *Account) *AccountState { |
||||
state := &AccountState{Nonce: account.Nonce, Account: account} |
||||
s.states[string(addr)] = state |
||||
return state |
||||
} |
||||
|
||||
func (s *AddrStateStore) Get(addr []byte) *AccountState { |
||||
return s.states[string(addr)] |
||||
} |
||||
|
||||
type AccountState struct { |
||||
Nonce uint64 |
||||
Account *Account |
||||
} |
@ -1,8 +0,0 @@ |
||||
package ethchain |
||||
|
||||
import ( |
||||
"testing" |
||||
) |
||||
|
||||
func TestAddressState(t *testing.T) { |
||||
} |
@ -0,0 +1,59 @@ |
||||
package ethchain |
||||
|
||||
import ( |
||||
"fmt" |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
"math/big" |
||||
) |
||||
|
||||
func Disassemble(script []byte) (asm []string) { |
||||
pc := new(big.Int) |
||||
for { |
||||
if pc.Cmp(big.NewInt(int64(len(script)))) >= 0 { |
||||
return |
||||
} |
||||
|
||||
// Get the memory location of pc
|
||||
val := script[pc.Int64()] |
||||
// Get the opcode (it must be an opcode!)
|
||||
op := OpCode(val) |
||||
|
||||
asm = append(asm, fmt.Sprintf("%v", op)) |
||||
|
||||
switch op { |
||||
case oPUSH: // Push PC+1 on to the stack
|
||||
pc.Add(pc, ethutil.Big1) |
||||
data := script[pc.Int64() : pc.Int64()+32] |
||||
val := ethutil.BigD(data) |
||||
|
||||
var b []byte |
||||
if val.Int64() == 0 { |
||||
b = []byte{0} |
||||
} else { |
||||
b = val.Bytes() |
||||
} |
||||
|
||||
asm = append(asm, fmt.Sprintf("0x%x", b)) |
||||
|
||||
pc.Add(pc, big.NewInt(31)) |
||||
case oPUSH20: |
||||
pc.Add(pc, ethutil.Big1) |
||||
data := script[pc.Int64() : pc.Int64()+20] |
||||
val := ethutil.BigD(data) |
||||
var b []byte |
||||
if val.Int64() == 0 { |
||||
b = []byte{0} |
||||
} else { |
||||
b = val.Bytes() |
||||
} |
||||
|
||||
asm = append(asm, fmt.Sprintf("0x%x", b)) |
||||
|
||||
pc.Add(pc, big.NewInt(19)) |
||||
} |
||||
|
||||
pc.Add(pc, ethutil.Big1) |
||||
} |
||||
|
||||
return |
||||
} |
@ -0,0 +1,115 @@ |
||||
package ethchain |
||||
|
||||
import ( |
||||
"fmt" |
||||
"github.com/ethereum/eth-go/ethdb" |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
"github.com/ethereum/eth-go/ethwire" |
||||
"testing" |
||||
) |
||||
|
||||
// Implement our EthTest Manager
|
||||
type TestManager struct { |
||||
stateManager *StateManager |
||||
reactor *ethutil.ReactorEngine |
||||
|
||||
txPool *TxPool |
||||
blockChain *BlockChain |
||||
Blocks []*Block |
||||
} |
||||
|
||||
func (s *TestManager) BlockChain() *BlockChain { |
||||
return s.blockChain |
||||
} |
||||
|
||||
func (tm *TestManager) TxPool() *TxPool { |
||||
return tm.txPool |
||||
} |
||||
|
||||
func (tm *TestManager) StateManager() *StateManager { |
||||
return tm.stateManager |
||||
} |
||||
|
||||
func (tm *TestManager) Reactor() *ethutil.ReactorEngine { |
||||
return tm.reactor |
||||
} |
||||
func (tm *TestManager) Broadcast(msgType ethwire.MsgType, data []interface{}) { |
||||
fmt.Println("Broadcast not implemented") |
||||
} |
||||
|
||||
func NewTestManager() *TestManager { |
||||
ethutil.ReadConfig(".ethtest") |
||||
|
||||
db, err := ethdb.NewMemDatabase() |
||||
if err != nil { |
||||
fmt.Println("Could not create mem-db, failing") |
||||
return nil |
||||
} |
||||
ethutil.Config.Db = db |
||||
|
||||
testManager := &TestManager{} |
||||
testManager.reactor = ethutil.NewReactorEngine() |
||||
|
||||
testManager.txPool = NewTxPool(testManager) |
||||
testManager.blockChain = NewBlockChain(testManager) |
||||
testManager.stateManager = NewStateManager(testManager) |
||||
|
||||
// Start the tx pool
|
||||
testManager.txPool.Start() |
||||
|
||||
return testManager |
||||
} |
||||
func (tm *TestManager) AddFakeBlock(blk []byte) error { |
||||
block := NewBlockFromBytes(blk) |
||||
tm.Blocks = append(tm.Blocks, block) |
||||
tm.StateManager().PrepareDefault(block) |
||||
err := tm.StateManager().ProcessBlock(block, false) |
||||
return err |
||||
} |
||||
func (tm *TestManager) CreateChain1() error { |
||||
err := tm.AddFakeBlock([]byte{248, 246, 248, 242, 160, 58, 253, 98, 206, 198, 181, 152, 223, 201, 116, 197, 154, 111, 104, 54, 113, 249, 184, 246, 15, 226, 142, 187, 47, 138, 60, 201, 66, 226, 237, 29, 7, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 184, 65, 4, 103, 109, 19, 120, 219, 91, 248, 48, 204, 17, 28, 7, 146, 72, 203, 15, 207, 251, 31, 216, 138, 26, 59, 34, 238, 40, 114, 233, 1, 13, 207, 90, 71, 136, 124, 86, 196, 127, 10, 176, 193, 154, 165, 76, 155, 154, 59, 45, 34, 96, 183, 212, 99, 41, 27, 40, 119, 171, 231, 160, 114, 56, 218, 173, 160, 80, 218, 177, 253, 147, 35, 101, 59, 37, 87, 97, 193, 119, 21, 132, 111, 93, 53, 152, 203, 38, 134, 25, 104, 138, 236, 92, 27, 176, 89, 229, 176, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 131, 63, 240, 0, 132, 83, 48, 32, 251, 128, 160, 4, 10, 11, 225, 132, 86, 146, 227, 229, 137, 164, 245, 16, 139, 219, 12, 251, 178, 154, 168, 210, 18, 84, 40, 250, 41, 124, 92, 169, 242, 246, 180, 192, 192}) |
||||
err = tm.AddFakeBlock([]byte{248, 246, 248, 242, 160, 222, 229, 152, 228, 200, 163, 244, 144, 120, 18, 203, 253, 195, 185, 105, 131, 163, 226, 116, 40, 140, 68, 249, 198, 221, 152, 121, 0, 124, 11, 180, 125, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 184, 65, 4, 103, 109, 19, 120, 219, 91, 248, 48, 204, 17, 28, 7, 146, 72, 203, 15, 207, 251, 31, 216, 138, 26, 59, 34, 238, 40, 114, 233, 1, 13, 207, 90, 71, 136, 124, 86, 196, 127, 10, 176, 193, 154, 165, 76, 155, 154, 59, 45, 34, 96, 183, 212, 99, 41, 27, 40, 119, 171, 231, 160, 114, 56, 218, 173, 160, 80, 218, 177, 253, 147, 35, 101, 59, 37, 87, 97, 193, 119, 21, 132, 111, 93, 53, 152, 203, 38, 134, 25, 104, 138, 236, 92, 27, 176, 89, 229, 176, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 131, 63, 224, 4, 132, 83, 48, 36, 250, 128, 160, 79, 58, 51, 246, 238, 249, 210, 253, 136, 83, 71, 134, 49, 114, 190, 189, 242, 78, 100, 238, 101, 84, 204, 176, 198, 25, 139, 151, 60, 84, 51, 126, 192, 192}) |
||||
err = tm.AddFakeBlock([]byte{248, 246, 248, 242, 160, 68, 52, 33, 210, 160, 189, 217, 255, 78, 37, 196, 217, 94, 247, 166, 169, 224, 199, 102, 110, 85, 213, 45, 13, 173, 106, 4, 103, 151, 195, 38, 86, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 184, 65, 4, 103, 109, 19, 120, 219, 91, 248, 48, 204, 17, 28, 7, 146, 72, 203, 15, 207, 251, 31, 216, 138, 26, 59, 34, 238, 40, 114, 233, 1, 13, 207, 90, 71, 136, 124, 86, 196, 127, 10, 176, 193, 154, 165, 76, 155, 154, 59, 45, 34, 96, 183, 212, 99, 41, 27, 40, 119, 171, 231, 160, 114, 56, 218, 173, 160, 80, 218, 177, 253, 147, 35, 101, 59, 37, 87, 97, 193, 119, 21, 132, 111, 93, 53, 152, 203, 38, 134, 25, 104, 138, 236, 92, 27, 176, 89, 229, 176, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 131, 63, 208, 12, 132, 83, 48, 38, 206, 128, 160, 65, 147, 32, 128, 177, 198, 131, 57, 57, 68, 135, 65, 198, 178, 138, 43, 25, 135, 92, 174, 208, 119, 103, 225, 26, 207, 243, 31, 225, 29, 173, 119, 192, 192}) |
||||
return err |
||||
} |
||||
func (tm *TestManager) CreateChain2() error { |
||||
err := tm.AddFakeBlock([]byte{248, 246, 248, 242, 160, 58, 253, 98, 206, 198, 181, 152, 223, 201, 116, 197, 154, 111, 104, 54, 113, 249, 184, 246, 15, 226, 142, 187, 47, 138, 60, 201, 66, 226, 237, 29, 7, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 184, 65, 4, 72, 201, 77, 81, 160, 103, 70, 18, 102, 204, 82, 192, 86, 157, 40, 30, 117, 218, 224, 202, 1, 36, 249, 88, 82, 210, 19, 156, 112, 31, 13, 117, 227, 0, 125, 221, 190, 165, 16, 193, 163, 161, 175, 33, 37, 184, 235, 62, 201, 93, 102, 185, 143, 54, 146, 114, 30, 253, 178, 245, 87, 38, 191, 214, 160, 80, 218, 177, 253, 147, 35, 101, 59, 37, 87, 97, 193, 119, 21, 132, 111, 93, 53, 152, 203, 38, 134, 25, 104, 138, 236, 92, 27, 176, 89, 229, 176, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 131, 63, 240, 0, 132, 83, 48, 40, 35, 128, 160, 162, 214, 119, 207, 212, 186, 64, 47, 14, 186, 98, 118, 203, 79, 172, 205, 33, 206, 225, 177, 225, 194, 98, 188, 63, 219, 13, 151, 47, 32, 204, 27, 192, 192}) |
||||
err = tm.AddFakeBlock([]byte{248, 246, 248, 242, 160, 0, 210, 76, 6, 13, 18, 219, 190, 18, 250, 23, 178, 198, 117, 254, 85, 14, 74, 104, 116, 56, 144, 116, 172, 14, 3, 236, 99, 248, 228, 142, 91, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 184, 65, 4, 72, 201, 77, 81, 160, 103, 70, 18, 102, 204, 82, 192, 86, 157, 40, 30, 117, 218, 224, 202, 1, 36, 249, 88, 82, 210, 19, 156, 112, 31, 13, 117, 227, 0, 125, 221, 190, 165, 16, 193, 163, 161, 175, 33, 37, 184, 235, 62, 201, 93, 102, 185, 143, 54, 146, 114, 30, 253, 178, 245, 87, 38, 191, 214, 160, 80, 218, 177, 253, 147, 35, 101, 59, 37, 87, 97, 193, 119, 21, 132, 111, 93, 53, 152, 203, 38, 134, 25, 104, 138, 236, 92, 27, 176, 89, 229, 176, 160, 29, 204, 77, 232, 222, 199, 93, 122, 171, 133, 181, 103, 182, 204, 212, 26, 211, 18, 69, 27, 148, 138, 116, 19, 240, 161, 66, 253, 64, 212, 147, 71, 131, 63, 255, 252, 132, 83, 48, 40, 74, 128, 160, 185, 20, 138, 2, 210, 15, 71, 144, 89, 167, 94, 155, 148, 118, 170, 157, 122, 70, 70, 114, 50, 221, 231, 8, 132, 167, 115, 239, 44, 245, 41, 226, 192, 192}) |
||||
return err |
||||
} |
||||
|
||||
func TestNegativeBlockChainReorg(t *testing.T) { |
||||
// We are resetting the database between creation so we need to cache our information
|
||||
testManager2 := NewTestManager() |
||||
testManager2.CreateChain2() |
||||
tm2Blocks := testManager2.Blocks |
||||
|
||||
testManager := NewTestManager() |
||||
testManager.CreateChain1() |
||||
oldState := testManager.BlockChain().CurrentBlock.State() |
||||
|
||||
if testManager.BlockChain().FindCanonicalChain(tm2Blocks, testManager.BlockChain().GenesisBlock().Hash()) != true { |
||||
t.Error("I expected TestManager to have the longest chain, but it was TestManager2 instead.") |
||||
} |
||||
if testManager.BlockChain().CurrentBlock.State() != oldState { |
||||
t.Error("I expected the top state to be the same as it was as before the reorg") |
||||
} |
||||
|
||||
} |
||||
|
||||
func TestPositiveBlockChainReorg(t *testing.T) { |
||||
testManager := NewTestManager() |
||||
testManager.CreateChain1() |
||||
tm1Blocks := testManager.Blocks |
||||
|
||||
testManager2 := NewTestManager() |
||||
testManager2.CreateChain2() |
||||
oldState := testManager2.BlockChain().CurrentBlock.State() |
||||
|
||||
if testManager2.BlockChain().FindCanonicalChain(tm1Blocks, testManager.BlockChain().GenesisBlock().Hash()) == true { |
||||
t.Error("I expected TestManager to have the longest chain, but it was TestManager2 instead.") |
||||
} |
||||
if testManager2.BlockChain().CurrentBlock.State() == oldState { |
||||
t.Error("I expected the top state to have been modified but it was not") |
||||
} |
||||
} |
@ -1,94 +0,0 @@ |
||||
package ethchain |
||||
|
||||
import ( |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
"math/big" |
||||
) |
||||
|
||||
type Contract struct { |
||||
Amount *big.Int |
||||
Nonce uint64 |
||||
//state *ethutil.Trie
|
||||
state *State |
||||
address []byte |
||||
} |
||||
|
||||
func NewContract(address []byte, Amount *big.Int, root []byte) *Contract { |
||||
contract := &Contract{address: address, Amount: Amount, Nonce: 0} |
||||
contract.state = NewState(ethutil.NewTrie(ethutil.Config.Db, string(root))) |
||||
|
||||
return contract |
||||
} |
||||
|
||||
func NewContractFromBytes(address, data []byte) *Contract { |
||||
contract := &Contract{address: address} |
||||
contract.RlpDecode(data) |
||||
|
||||
return contract |
||||
} |
||||
|
||||
func (c *Contract) Addr(addr []byte) *ethutil.Value { |
||||
return ethutil.NewValueFromBytes([]byte(c.state.trie.Get(string(addr)))) |
||||
} |
||||
|
||||
func (c *Contract) SetAddr(addr []byte, value interface{}) { |
||||
c.state.trie.Update(string(addr), string(ethutil.NewValue(value).Encode())) |
||||
} |
||||
|
||||
func (c *Contract) State() *State { |
||||
return c.state |
||||
} |
||||
|
||||
func (c *Contract) GetMem(num *big.Int) *ethutil.Value { |
||||
nb := ethutil.BigToBytes(num, 256) |
||||
|
||||
return c.Addr(nb) |
||||
} |
||||
|
||||
func (c *Contract) SetMem(num *big.Int, val *ethutil.Value) { |
||||
addr := ethutil.BigToBytes(num, 256) |
||||
c.state.trie.Update(string(addr), string(val.Encode())) |
||||
} |
||||
|
||||
// Return the gas back to the origin. Used by the Virtual machine or Closures
|
||||
func (c *Contract) ReturnGas(val *big.Int, state *State) { |
||||
c.Amount.Add(c.Amount, val) |
||||
} |
||||
|
||||
func (c *Contract) Address() []byte { |
||||
return c.address |
||||
} |
||||
|
||||
func (c *Contract) RlpEncode() []byte { |
||||
return ethutil.Encode([]interface{}{c.Amount, c.Nonce, c.state.trie.Root}) |
||||
} |
||||
|
||||
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 MakeContract(tx *Transaction, state *State) *Contract { |
||||
// Create contract if there's no recipient
|
||||
if tx.IsContract() { |
||||
addr := tx.Hash()[12:] |
||||
|
||||
value := tx.Value |
||||
contract := NewContract(addr, value, []byte("")) |
||||
state.trie.Update(string(addr), string(contract.RlpEncode())) |
||||
for i, val := range tx.Data { |
||||
if len(val) > 0 { |
||||
bytNum := ethutil.BigToBytes(big.NewInt(int64(i)), 256) |
||||
contract.state.trie.Update(string(bytNum), string(ethutil.Encode(val))) |
||||
} |
||||
} |
||||
state.trie.Update(string(addr), string(contract.RlpEncode())) |
||||
|
||||
return contract |
||||
} |
||||
|
||||
return nil |
||||
} |
@ -0,0 +1,194 @@ |
||||
package ethchain |
||||
|
||||
import ( |
||||
"fmt" |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
"math/big" |
||||
) |
||||
|
||||
type StateObject struct { |
||||
// Address of the object
|
||||
address []byte |
||||
// Shared attributes
|
||||
Amount *big.Int |
||||
Nonce uint64 |
||||
// Contract related attributes
|
||||
state *State |
||||
script []byte |
||||
initScript []byte |
||||
} |
||||
|
||||
// Converts an transaction in to a state object
|
||||
func MakeContract(tx *Transaction, state *State) *StateObject { |
||||
// Create contract if there's no recipient
|
||||
if tx.IsContract() { |
||||
// FIXME
|
||||
addr := tx.Hash()[12:] |
||||
|
||||
value := tx.Value |
||||
contract := NewContract(addr, value, []byte("")) |
||||
state.UpdateStateObject(contract) |
||||
|
||||
contract.script = tx.Data |
||||
contract.initScript = tx.Init |
||||
|
||||
state.UpdateStateObject(contract) |
||||
|
||||
return contract |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func NewContract(address []byte, Amount *big.Int, root []byte) *StateObject { |
||||
contract := &StateObject{address: address, Amount: Amount, Nonce: 0} |
||||
contract.state = NewState(ethutil.NewTrie(ethutil.Config.Db, string(root))) |
||||
|
||||
return contract |
||||
} |
||||
|
||||
// Returns a newly created account
|
||||
func NewAccount(address []byte, amount *big.Int) *StateObject { |
||||
account := &StateObject{address: address, Amount: amount, Nonce: 0} |
||||
|
||||
return account |
||||
} |
||||
|
||||
func NewStateObjectFromBytes(address, data []byte) *StateObject { |
||||
object := &StateObject{address: address} |
||||
object.RlpDecode(data) |
||||
|
||||
return object |
||||
} |
||||
|
||||
func (c *StateObject) State() *State { |
||||
return c.state |
||||
} |
||||
|
||||
func (c *StateObject) N() *big.Int { |
||||
return big.NewInt(int64(c.Nonce)) |
||||
} |
||||
|
||||
func (c *StateObject) Addr(addr []byte) *ethutil.Value { |
||||
return ethutil.NewValueFromBytes([]byte(c.state.trie.Get(string(addr)))) |
||||
} |
||||
|
||||
func (c *StateObject) SetAddr(addr []byte, value interface{}) { |
||||
c.state.trie.Update(string(addr), string(ethutil.NewValue(value).Encode())) |
||||
} |
||||
|
||||
func (c *StateObject) SetMem(num *big.Int, val *ethutil.Value) { |
||||
addr := ethutil.BigToBytes(num, 256) |
||||
c.SetAddr(addr, val) |
||||
} |
||||
|
||||
func (c *StateObject) GetMem(num *big.Int) *ethutil.Value { |
||||
nb := ethutil.BigToBytes(num, 256) |
||||
|
||||
return c.Addr(nb) |
||||
} |
||||
|
||||
func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value { |
||||
if int64(len(c.script)-1) < pc.Int64() { |
||||
return ethutil.NewValue(0) |
||||
} |
||||
|
||||
return ethutil.NewValueFromBytes([]byte{c.script[pc.Int64()]}) |
||||
} |
||||
|
||||
// Return the gas back to the origin. Used by the Virtual machine or Closures
|
||||
func (c *StateObject) ReturnGas(gas, price *big.Int, state *State) { |
||||
remainder := new(big.Int).Mul(gas, price) |
||||
c.AddAmount(remainder) |
||||
} |
||||
|
||||
func (c *StateObject) AddAmount(amount *big.Int) { |
||||
c.SetAmount(new(big.Int).Add(c.Amount, amount)) |
||||
} |
||||
|
||||
func (c *StateObject) SubAmount(amount *big.Int) { |
||||
c.SetAmount(new(big.Int).Sub(c.Amount, amount)) |
||||
} |
||||
|
||||
func (c *StateObject) SetAmount(amount *big.Int) { |
||||
c.Amount = amount |
||||
} |
||||
|
||||
func (c *StateObject) ConvertGas(gas, price *big.Int) error { |
||||
total := new(big.Int).Mul(gas, price) |
||||
if total.Cmp(c.Amount) > 0 { |
||||
return fmt.Errorf("insufficient amount: %v, %v", c.Amount, total) |
||||
} |
||||
|
||||
c.SubAmount(total) |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// Returns the address of the contract/account
|
||||
func (c *StateObject) Address() []byte { |
||||
return c.address |
||||
} |
||||
|
||||
// Returns the main script body
|
||||
func (c *StateObject) Script() []byte { |
||||
return c.script |
||||
} |
||||
|
||||
// Returns the initialization script
|
||||
func (c *StateObject) Init() []byte { |
||||
return c.initScript |
||||
} |
||||
|
||||
// State object encoding methods
|
||||
func (c *StateObject) RlpEncode() []byte { |
||||
var root interface{} |
||||
if c.state != nil { |
||||
root = c.state.trie.Root |
||||
} else { |
||||
root = nil |
||||
} |
||||
return ethutil.Encode([]interface{}{c.Amount, c.Nonce, root, c.script}) |
||||
} |
||||
|
||||
func (c *StateObject) 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())) |
||||
c.script = decoder.Get(3).Bytes() |
||||
} |
||||
|
||||
// The cached state and state object cache are helpers which will give you somewhat
|
||||
// control over the nonce. When creating new transactions you're interested in the 'next'
|
||||
// nonce rather than the current nonce. This to avoid creating invalid-nonce transactions.
|
||||
type StateObjectCache struct { |
||||
cachedObjects map[string]*CachedStateObject |
||||
} |
||||
|
||||
func NewStateObjectCache() *StateObjectCache { |
||||
return &StateObjectCache{cachedObjects: make(map[string]*CachedStateObject)} |
||||
} |
||||
|
||||
func (s *StateObjectCache) Add(addr []byte, object *StateObject) *CachedStateObject { |
||||
state := &CachedStateObject{Nonce: object.Nonce, Object: object} |
||||
s.cachedObjects[string(addr)] = state |
||||
|
||||
return state |
||||
} |
||||
|
||||
func (s *StateObjectCache) Get(addr []byte) *CachedStateObject { |
||||
return s.cachedObjects[string(addr)] |
||||
} |
||||
|
||||
type CachedStateObject struct { |
||||
Nonce uint64 |
||||
Object *StateObject |
||||
} |
||||
|
||||
type StorageState struct { |
||||
StateAddress []byte |
||||
Address []byte |
||||
Value *big.Int |
||||
} |
@ -0,0 +1,230 @@ |
||||
package ethchain |
||||
|
||||
type OpCode int |
||||
|
||||
// Op codes
|
||||
const ( |
||||
// 0x0 range - arithmetic ops
|
||||
oSTOP = 0x00 |
||||
oADD = 0x01 |
||||
oMUL = 0x02 |
||||
oSUB = 0x03 |
||||
oDIV = 0x04 |
||||
oSDIV = 0x05 |
||||
oMOD = 0x06 |
||||
oSMOD = 0x07 |
||||
oEXP = 0x08 |
||||
oNEG = 0x09 |
||||
oLT = 0x0a |
||||
oGT = 0x0b |
||||
oEQ = 0x0c |
||||
oNOT = 0x0d |
||||
|
||||
// 0x10 range - bit ops
|
||||
oAND = 0x10 |
||||
oOR = 0x11 |
||||
oXOR = 0x12 |
||||
oBYTE = 0x13 |
||||
|
||||
// 0x20 range - crypto
|
||||
oSHA3 = 0x20 |
||||
|
||||
// 0x30 range - closure state
|
||||
oADDRESS = 0x30 |
||||
oBALANCE = 0x31 |
||||
oORIGIN = 0x32 |
||||
oCALLER = 0x33 |
||||
oCALLVALUE = 0x34 |
||||
oCALLDATALOAD = 0x35 |
||||
oCALLDATASIZE = 0x36 |
||||
oGASPRICE = 0x37 |
||||
|
||||
// 0x40 range - block operations
|
||||
oPREVHASH = 0x40 |
||||
oCOINBASE = 0x41 |
||||
oTIMESTAMP = 0x42 |
||||
oNUMBER = 0x43 |
||||
oDIFFICULTY = 0x44 |
||||
oGASLIMIT = 0x45 |
||||
|
||||
// 0x50 range - 'storage' and execution
|
||||
oPUSH = 0x50 |
||||
oPUSH20 = 0x80 |
||||
oPOP = 0x51 |
||||
oDUP = 0x52 |
||||
oSWAP = 0x53 |
||||
oMLOAD = 0x54 |
||||
oMSTORE = 0x55 |
||||
oMSTORE8 = 0x56 |
||||
oSLOAD = 0x57 |
||||
oSSTORE = 0x58 |
||||
oJUMP = 0x59 |
||||
oJUMPI = 0x5a |
||||
oPC = 0x5b |
||||
oMSIZE = 0x5c |
||||
|
||||
// 0x60 range - closures
|
||||
oCREATE = 0x60 |
||||
oCALL = 0x61 |
||||
oRETURN = 0x62 |
||||
|
||||
// 0x70 range - other
|
||||
oLOG = 0x70 // XXX Unofficial
|
||||
oSUICIDE = 0x7f |
||||
) |
||||
|
||||
// Since the opcodes aren't all in order we can't use a regular slice
|
||||
var opCodeToString = map[OpCode]string{ |
||||
// 0x0 range - arithmetic ops
|
||||
oSTOP: "STOP", |
||||
oADD: "ADD", |
||||
oMUL: "MUL", |
||||
oSUB: "SUB", |
||||
oDIV: "DIV", |
||||
oSDIV: "SDIV", |
||||
oMOD: "MOD", |
||||
oSMOD: "SMOD", |
||||
oEXP: "EXP", |
||||
oNEG: "NEG", |
||||
oLT: "LT", |
||||
oGT: "GT", |
||||
oEQ: "EQ", |
||||
oNOT: "NOT", |
||||
|
||||
// 0x10 range - bit ops
|
||||
oAND: "AND", |
||||
oOR: "OR", |
||||
oXOR: "XOR", |
||||
oBYTE: "BYTE", |
||||
|
||||
// 0x20 range - crypto
|
||||
oSHA3: "SHA3", |
||||
|
||||
// 0x30 range - closure state
|
||||
oADDRESS: "ADDRESS", |
||||
oBALANCE: "BALANCE", |
||||
oORIGIN: "ORIGIN", |
||||
oCALLER: "CALLER", |
||||
oCALLVALUE: "CALLVALUE", |
||||
oCALLDATALOAD: "CALLDATALOAD", |
||||
oCALLDATASIZE: "CALLDATASIZE", |
||||
oGASPRICE: "TXGASPRICE", |
||||
|
||||
// 0x40 range - block operations
|
||||
oPREVHASH: "PREVHASH", |
||||
oCOINBASE: "COINBASE", |
||||
oTIMESTAMP: "TIMESTAMP", |
||||
oNUMBER: "NUMBER", |
||||
oDIFFICULTY: "DIFFICULTY", |
||||
oGASLIMIT: "GASLIMIT", |
||||
|
||||
// 0x50 range - 'storage' and execution
|
||||
oPUSH: "PUSH", |
||||
oPOP: "POP", |
||||
oDUP: "DUP", |
||||
oSWAP: "SWAP", |
||||
oMLOAD: "MLOAD", |
||||
oMSTORE: "MSTORE", |
||||
oMSTORE8: "MSTORE8", |
||||
oSLOAD: "SLOAD", |
||||
oSSTORE: "SSTORE", |
||||
oJUMP: "JUMP", |
||||
oJUMPI: "JUMPI", |
||||
oPC: "PC", |
||||
oMSIZE: "MSIZE", |
||||
|
||||
// 0x60 range - closures
|
||||
oCREATE: "CREATE", |
||||
oCALL: "CALL", |
||||
oRETURN: "RETURN", |
||||
|
||||
// 0x70 range - other
|
||||
oLOG: "LOG", |
||||
oSUICIDE: "SUICIDE", |
||||
} |
||||
|
||||
func (o OpCode) String() string { |
||||
return opCodeToString[o] |
||||
} |
||||
|
||||
// Op codes for assembling
|
||||
var OpCodes = map[string]byte{ |
||||
// 0x0 range - arithmetic ops
|
||||
"STOP": 0x00, |
||||
"ADD": 0x01, |
||||
"MUL": 0x02, |
||||
"SUB": 0x03, |
||||
"DIV": 0x04, |
||||
"SDIV": 0x05, |
||||
"MOD": 0x06, |
||||
"SMOD": 0x07, |
||||
"EXP": 0x08, |
||||
"NEG": 0x09, |
||||
"LT": 0x0a, |
||||
"GT": 0x0b, |
||||
"EQ": 0x0c, |
||||
"NOT": 0x0d, |
||||
|
||||
// 0x10 range - bit ops
|
||||
"AND": 0x10, |
||||
"OR": 0x11, |
||||
"XOR": 0x12, |
||||
"BYTE": 0x13, |
||||
|
||||
// 0x20 range - crypto
|
||||
"SHA3": 0x20, |
||||
|
||||
// 0x30 range - closure state
|
||||
"ADDRESS": 0x30, |
||||
"BALANCE": 0x31, |
||||
"ORIGIN": 0x32, |
||||
"CALLER": 0x33, |
||||
"CALLVALUE": 0x34, |
||||
"CALLDATALOAD": 0x35, |
||||
"CALLDATASIZE": 0x36, |
||||
"GASPRICE": 0x38, |
||||
|
||||
// 0x40 range - block operations
|
||||
"PREVHASH": 0x40, |
||||
"COINBASE": 0x41, |
||||
"TIMESTAMP": 0x42, |
||||
"NUMBER": 0x43, |
||||
"DIFFICULTY": 0x44, |
||||
"GASLIMIT": 0x45, |
||||
|
||||
// 0x50 range - 'storage' and execution
|
||||
"PUSH": 0x50, |
||||
|
||||
"PUSH20": 0x80, |
||||
|
||||
"POP": 0x51, |
||||
"DUP": 0x52, |
||||
"SWAP": 0x53, |
||||
"MLOAD": 0x54, |
||||
"MSTORE": 0x55, |
||||
"MSTORE8": 0x56, |
||||
"SLOAD": 0x57, |
||||
"SSTORE": 0x58, |
||||
"JUMP": 0x59, |
||||
"JUMPI": 0x5a, |
||||
"PC": 0x5b, |
||||
"MSIZE": 0x5c, |
||||
|
||||
// 0x60 range - closures
|
||||
"CREATE": 0x60, |
||||
"CALL": 0x61, |
||||
"RETURN": 0x62, |
||||
|
||||
// 0x70 range - other
|
||||
"LOG": 0x70, |
||||
"SUICIDE": 0x7f, |
||||
} |
||||
|
||||
func IsOpCode(s string) bool { |
||||
for key, _ := range OpCodes { |
||||
if key == s { |
||||
return true |
||||
} |
||||
} |
||||
return false |
||||
} |
@ -0,0 +1,156 @@ |
||||
package ethminer |
||||
|
||||
import ( |
||||
"bytes" |
||||
"github.com/ethereum/eth-go/ethchain" |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
"github.com/ethereum/eth-go/ethwire" |
||||
"log" |
||||
) |
||||
|
||||
type Miner struct { |
||||
pow ethchain.PoW |
||||
ethereum ethchain.EthManager |
||||
coinbase []byte |
||||
reactChan chan ethutil.React |
||||
txs []*ethchain.Transaction |
||||
uncles []*ethchain.Block |
||||
block *ethchain.Block |
||||
powChan chan []byte |
||||
quitChan chan ethutil.React |
||||
} |
||||
|
||||
func NewDefaultMiner(coinbase []byte, ethereum ethchain.EthManager) Miner { |
||||
reactChan := make(chan ethutil.React, 1) // This is the channel that receives 'updates' when ever a new transaction or block comes in
|
||||
powChan := make(chan []byte, 1) // This is the channel that receives valid sha hases for a given block
|
||||
quitChan := make(chan ethutil.React, 1) // This is the channel that can exit the miner thread
|
||||
|
||||
ethereum.Reactor().Subscribe("newBlock", reactChan) |
||||
ethereum.Reactor().Subscribe("newTx", reactChan) |
||||
|
||||
// We need the quit chan to be a Reactor event.
|
||||
// The POW search method is actually blocking and if we don't
|
||||
// listen to the reactor events inside of the pow itself
|
||||
// The miner overseer will never get the reactor events themselves
|
||||
// Only after the miner will find the sha
|
||||
ethereum.Reactor().Subscribe("newBlock", quitChan) |
||||
ethereum.Reactor().Subscribe("newTx", quitChan) |
||||
|
||||
miner := Miner{ |
||||
pow: ðchain.EasyPow{}, |
||||
ethereum: ethereum, |
||||
coinbase: coinbase, |
||||
reactChan: reactChan, |
||||
powChan: powChan, |
||||
quitChan: quitChan, |
||||
} |
||||
|
||||
// Insert initial TXs in our little miner 'pool'
|
||||
miner.txs = ethereum.TxPool().Flush() |
||||
miner.block = ethereum.BlockChain().NewBlock(miner.coinbase, miner.txs) |
||||
|
||||
return miner |
||||
} |
||||
func (miner *Miner) Start() { |
||||
// Prepare inital block
|
||||
miner.ethereum.StateManager().Prepare(miner.block.State(), miner.block.State()) |
||||
go func() { miner.listener() }() |
||||
} |
||||
func (miner *Miner) listener() { |
||||
for { |
||||
select { |
||||
case chanMessage := <-miner.reactChan: |
||||
if block, ok := chanMessage.Resource.(*ethchain.Block); ok { |
||||
log.Println("[MINER] Got new block via Reactor") |
||||
if bytes.Compare(miner.ethereum.BlockChain().CurrentBlock.Hash(), block.Hash()) == 0 { |
||||
// TODO: Perhaps continue mining to get some uncle rewards
|
||||
log.Println("[MINER] New top block found resetting state") |
||||
|
||||
// Filter out which Transactions we have that were not in this block
|
||||
var newtxs []*ethchain.Transaction |
||||
for _, tx := range miner.txs { |
||||
found := false |
||||
for _, othertx := range block.Transactions() { |
||||
if bytes.Compare(tx.Hash(), othertx.Hash()) == 0 { |
||||
found = true |
||||
} |
||||
} |
||||
if found == false { |
||||
newtxs = append(newtxs, tx) |
||||
} |
||||
} |
||||
miner.txs = newtxs |
||||
|
||||
// Setup a fresh state to mine on
|
||||
miner.block = miner.ethereum.BlockChain().NewBlock(miner.coinbase, miner.txs) |
||||
|
||||
} else { |
||||
if bytes.Compare(block.PrevHash, miner.ethereum.BlockChain().CurrentBlock.PrevHash) == 0 { |
||||
log.Println("[MINER] Adding uncle block") |
||||
miner.uncles = append(miner.uncles, block) |
||||
miner.ethereum.StateManager().Prepare(miner.block.State(), miner.block.State()) |
||||
} |
||||
} |
||||
} |
||||
|
||||
if tx, ok := chanMessage.Resource.(*ethchain.Transaction); ok { |
||||
//log.Println("[MINER] Got new transaction from Reactor", tx)
|
||||
found := false |
||||
for _, ctx := range miner.txs { |
||||
if found = bytes.Compare(ctx.Hash(), tx.Hash()) == 0; found { |
||||
break |
||||
} |
||||
|
||||
} |
||||
if found == false { |
||||
//log.Println("[MINER] We did not know about this transaction, adding")
|
||||
miner.txs = append(miner.txs, tx) |
||||
miner.block = miner.ethereum.BlockChain().NewBlock(miner.coinbase, miner.txs) |
||||
miner.block.SetTransactions(miner.txs) |
||||
} else { |
||||
//log.Println("[MINER] We already had this transaction, ignoring")
|
||||
} |
||||
} |
||||
default: |
||||
log.Println("[MINER] Mining on block. Includes", len(miner.txs), "transactions") |
||||
|
||||
// Apply uncles
|
||||
if len(miner.uncles) > 0 { |
||||
miner.block.SetUncles(miner.uncles) |
||||
} |
||||
|
||||
// FIXME @ maranh, first block doesn't need this. Everything after the first block does.
|
||||
// Please check and fix
|
||||
miner.ethereum.StateManager().Prepare(miner.block.State(), miner.block.State()) |
||||
// Apply all transactions to the block
|
||||
miner.ethereum.StateManager().ApplyTransactions(miner.block, miner.block.Transactions()) |
||||
miner.ethereum.StateManager().AccumelateRewards(miner.block) |
||||
|
||||
// Search the nonce
|
||||
//log.Println("[MINER] Initialision complete, starting mining")
|
||||
miner.block.Nonce = miner.pow.Search(miner.block, miner.quitChan) |
||||
if miner.block.Nonce != nil { |
||||
miner.ethereum.StateManager().PrepareDefault(miner.block) |
||||
err := miner.ethereum.StateManager().ProcessBlock(miner.block, true) |
||||
if err != nil { |
||||
log.Println(err) |
||||
miner.txs = []*ethchain.Transaction{} // Move this somewhere neat
|
||||
miner.block = miner.ethereum.BlockChain().NewBlock(miner.coinbase, miner.txs) |
||||
} else { |
||||
|
||||
/* |
||||
// XXX @maranh This is already done in the state manager, why a 2nd time?
|
||||
if !miner.ethereum.StateManager().Pow.Verify(miner.block.HashNoNonce(), miner.block.Difficulty, miner.block.Nonce) { |
||||
log.Printf("Second stage verification error: Block's nonce is invalid (= %v)\n", ethutil.Hex(miner.block.Nonce)) |
||||
} |
||||
*/ |
||||
miner.ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{miner.block.Value().Val}) |
||||
log.Printf("[MINER] 🔨 Mined block %x\n", miner.block.Hash()) |
||||
|
||||
miner.txs = []*ethchain.Transaction{} // Move this somewhere neat
|
||||
miner.block = miner.ethereum.BlockChain().NewBlock(miner.coinbase, miner.txs) |
||||
} |
||||
} |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,147 @@ |
||||
package ethpub |
||||
|
||||
import ( |
||||
"github.com/ethereum/eth-go/ethchain" |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
) |
||||
|
||||
type PEthereum struct { |
||||
stateManager *ethchain.StateManager |
||||
blockChain *ethchain.BlockChain |
||||
txPool *ethchain.TxPool |
||||
} |
||||
|
||||
func NewPEthereum(sm *ethchain.StateManager, bc *ethchain.BlockChain, txp *ethchain.TxPool) *PEthereum { |
||||
return &PEthereum{ |
||||
sm, |
||||
bc, |
||||
txp, |
||||
} |
||||
} |
||||
|
||||
func (lib *PEthereum) GetBlock(hexHash string) *PBlock { |
||||
hash := ethutil.FromHex(hexHash) |
||||
|
||||
block := lib.blockChain.GetBlock(hash) |
||||
|
||||
var blockInfo *PBlock |
||||
|
||||
if block != nil { |
||||
blockInfo = &PBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Hex(block.Hash())} |
||||
} else { |
||||
blockInfo = &PBlock{Number: -1, Hash: ""} |
||||
} |
||||
|
||||
return blockInfo |
||||
} |
||||
|
||||
func (lib *PEthereum) GetKey() *PKey { |
||||
keyPair, err := ethchain.NewKeyPairFromSec(ethutil.Config.Db.GetKeys()[0].PrivateKey) |
||||
if err != nil { |
||||
return nil |
||||
} |
||||
|
||||
return NewPKey(keyPair) |
||||
} |
||||
|
||||
func (lib *PEthereum) GetStateObject(address string) *PStateObject { |
||||
stateObject := lib.stateManager.ProcState().GetContract(ethutil.FromHex(address)) |
||||
if stateObject != nil { |
||||
return NewPStateObject(stateObject) |
||||
} |
||||
|
||||
// See GetStorage for explanation on "nil"
|
||||
return NewPStateObject(nil) |
||||
} |
||||
|
||||
func (lib *PEthereum) GetStorage(address, storageAddress string) string { |
||||
return lib.GetStateObject(address).GetStorage(storageAddress) |
||||
} |
||||
|
||||
func (lib *PEthereum) GetTxCount(address string) int { |
||||
return lib.GetStateObject(address).Nonce() |
||||
} |
||||
|
||||
func (lib *PEthereum) IsContract(address string) bool { |
||||
return lib.GetStateObject(address).IsContract() |
||||
} |
||||
|
||||
func (lib *PEthereum) SecretToAddress(key string) string { |
||||
pair, err := ethchain.NewKeyPairFromSec(ethutil.FromHex(key)) |
||||
if err != nil { |
||||
return "" |
||||
} |
||||
|
||||
return ethutil.Hex(pair.Address()) |
||||
} |
||||
|
||||
func (lib *PEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) (*PReceipt, error) { |
||||
return lib.createTx(key, recipient, valueStr, gasStr, gasPriceStr, dataStr, "") |
||||
} |
||||
|
||||
func (lib *PEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) (*PReceipt, error) { |
||||
return lib.createTx(key, "", valueStr, gasStr, gasPriceStr, initStr, bodyStr) |
||||
} |
||||
|
||||
func (lib *PEthereum) createTx(key, recipient, valueStr, gasStr, gasPriceStr, initStr, scriptStr string) (*PReceipt, error) { |
||||
var hash []byte |
||||
var contractCreation bool |
||||
if len(recipient) == 0 { |
||||
contractCreation = true |
||||
} else { |
||||
hash = ethutil.FromHex(recipient) |
||||
} |
||||
|
||||
keyPair, err := ethchain.NewKeyPairFromSec([]byte(ethutil.FromHex(key))) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
value := ethutil.Big(valueStr) |
||||
gas := ethutil.Big(gasStr) |
||||
gasPrice := ethutil.Big(gasPriceStr) |
||||
var tx *ethchain.Transaction |
||||
// Compile and assemble the given data
|
||||
if contractCreation { |
||||
var initScript, mainScript []byte |
||||
var err error |
||||
if ethutil.IsHex(initStr) { |
||||
initScript = ethutil.FromHex(initStr[2:]) |
||||
} else { |
||||
initScript, err = ethutil.Compile(initStr) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
} |
||||
|
||||
if ethutil.IsHex(scriptStr) { |
||||
mainScript = ethutil.FromHex(scriptStr[2:]) |
||||
} else { |
||||
mainScript, err = ethutil.Compile(scriptStr) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
} |
||||
|
||||
tx = ethchain.NewContractCreationTx(value, gas, gasPrice, mainScript, initScript) |
||||
} else { |
||||
// Just in case it was submitted as a 0x prefixed string
|
||||
if len(initStr) > 0 && initStr[0:2] == "0x" { |
||||
initStr = initStr[2:len(initStr)] |
||||
} |
||||
tx = ethchain.NewTransactionMessage(hash, value, gas, gasPrice, ethutil.FromHex(initStr)) |
||||
} |
||||
|
||||
acc := lib.stateManager.GetAddrState(keyPair.Address()) |
||||
tx.Nonce = acc.Nonce |
||||
tx.Sign(keyPair.PrivateKey) |
||||
lib.txPool.QueueTransaction(tx) |
||||
|
||||
if contractCreation { |
||||
ethutil.Config.Log.Infof("Contract addr %x", tx.CreationAddress()) |
||||
} else { |
||||
ethutil.Config.Log.Infof("Tx hash %x", tx.Hash()) |
||||
} |
||||
|
||||
return NewPReciept(contractCreation, tx.CreationAddress(), tx.Hash(), keyPair.Address()), nil |
||||
} |
@ -0,0 +1,123 @@ |
||||
package ethpub |
||||
|
||||
import ( |
||||
"encoding/hex" |
||||
"github.com/ethereum/eth-go/ethchain" |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
) |
||||
|
||||
// Block interface exposed to QML
|
||||
type PBlock struct { |
||||
Number int `json:"number"` |
||||
Hash string `json:"hash"` |
||||
} |
||||
|
||||
// Creates a new QML Block from a chain block
|
||||
func NewPBlock(block *ethchain.Block) *PBlock { |
||||
info := block.BlockInfo() |
||||
hash := hex.EncodeToString(block.Hash()) |
||||
|
||||
return &PBlock{Number: int(info.Number), Hash: hash} |
||||
} |
||||
|
||||
type PTx struct { |
||||
Value, Hash, Address string |
||||
Contract bool |
||||
} |
||||
|
||||
func NewPTx(tx *ethchain.Transaction) *PTx { |
||||
hash := hex.EncodeToString(tx.Hash()) |
||||
sender := hex.EncodeToString(tx.Recipient) |
||||
isContract := len(tx.Data) > 0 |
||||
|
||||
return &PTx{Hash: hash, Value: ethutil.CurrencyToString(tx.Value), Address: sender, Contract: isContract} |
||||
} |
||||
|
||||
type PKey struct { |
||||
Address string `json:"address"` |
||||
PrivateKey string `json:"privateKey"` |
||||
PublicKey string `json:"publicKey"` |
||||
} |
||||
|
||||
func NewPKey(key *ethchain.KeyPair) *PKey { |
||||
return &PKey{ethutil.Hex(key.Address()), ethutil.Hex(key.PrivateKey), ethutil.Hex(key.PublicKey)} |
||||
} |
||||
|
||||
type PReceipt struct { |
||||
CreatedContract bool `json:"createdContract"` |
||||
Address string `json:"address"` |
||||
Hash string `json:"hash"` |
||||
Sender string `json:"sender"` |
||||
} |
||||
|
||||
func NewPReciept(contractCreation bool, creationAddress, hash, address []byte) *PReceipt { |
||||
return &PReceipt{ |
||||
contractCreation, |
||||
ethutil.Hex(creationAddress), |
||||
ethutil.Hex(hash), |
||||
ethutil.Hex(address), |
||||
} |
||||
} |
||||
|
||||
type PStateObject struct { |
||||
object *ethchain.StateObject |
||||
} |
||||
|
||||
func NewPStateObject(object *ethchain.StateObject) *PStateObject { |
||||
return &PStateObject{object: object} |
||||
} |
||||
|
||||
func (c *PStateObject) GetStorage(address string) string { |
||||
// Because somehow, even if you return nil to QML it
|
||||
// still has some magical object so we can't rely on
|
||||
// undefined or null at the QML side
|
||||
if c.object != nil { |
||||
val := c.object.GetMem(ethutil.Big("0x" + address)) |
||||
|
||||
return val.BigInt().String() |
||||
} |
||||
|
||||
return "" |
||||
} |
||||
|
||||
func (c *PStateObject) Value() string { |
||||
if c.object != nil { |
||||
return c.object.Amount.String() |
||||
} |
||||
|
||||
return "" |
||||
} |
||||
|
||||
func (c *PStateObject) Address() string { |
||||
if c.object != nil { |
||||
return ethutil.Hex(c.object.Address()) |
||||
} |
||||
|
||||
return "" |
||||
} |
||||
|
||||
func (c *PStateObject) Nonce() int { |
||||
if c.object != nil { |
||||
return int(c.object.Nonce) |
||||
} |
||||
|
||||
return 0 |
||||
} |
||||
|
||||
func (c *PStateObject) IsContract() bool { |
||||
if c.object != nil { |
||||
return len(c.object.Script()) > 0 |
||||
} |
||||
|
||||
return false |
||||
} |
||||
|
||||
type PStorageState struct { |
||||
StateAddress string |
||||
Address string |
||||
Value string |
||||
} |
||||
|
||||
func NewPStorageState(storageObject *ethchain.StorageState) *PStorageState { |
||||
return &PStorageState{ethutil.Hex(storageObject.StateAddress), ethutil.Hex(storageObject.Address), storageObject.Value.String()} |
||||
} |
@ -0,0 +1,215 @@ |
||||
package ethrpc |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"errors" |
||||
"github.com/ethereum/eth-go/ethpub" |
||||
_ "log" |
||||
) |
||||
|
||||
type EthereumApi struct { |
||||
ethp *ethpub.PEthereum |
||||
} |
||||
|
||||
type JsonArgs interface { |
||||
requirements() error |
||||
} |
||||
|
||||
type BlockResponse struct { |
||||
JsonResponse |
||||
} |
||||
type GetBlockArgs struct { |
||||
BlockNumber int |
||||
Hash string |
||||
} |
||||
|
||||
type ErrorResponse struct { |
||||
Error bool `json:"error"` |
||||
ErrorText string `json:"errorText"` |
||||
} |
||||
|
||||
type JsonResponse interface { |
||||
} |
||||
|
||||
type SuccessRes struct { |
||||
Error bool `json:"error"` |
||||
Result JsonResponse `json:"result"` |
||||
} |
||||
|
||||
func NewSuccessRes(object JsonResponse) string { |
||||
e := SuccessRes{Error: false, Result: object} |
||||
res, err := json.Marshal(e) |
||||
if err != nil { |
||||
// This should never happen
|
||||
panic("Creating json error response failed, help") |
||||
} |
||||
success := string(res) |
||||
return success |
||||
} |
||||
|
||||
func NewErrorResponse(msg string) error { |
||||
e := ErrorResponse{Error: true, ErrorText: msg} |
||||
res, err := json.Marshal(e) |
||||
if err != nil { |
||||
// This should never happen
|
||||
panic("Creating json error response failed, help") |
||||
} |
||||
newErr := errors.New(string(res)) |
||||
return newErr |
||||
} |
||||
|
||||
func (b *GetBlockArgs) requirements() error { |
||||
if b.BlockNumber == 0 && b.Hash == "" { |
||||
return NewErrorResponse("GetBlock requires either a block 'number' or a block 'hash' as argument") |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (p *EthereumApi) GetBlock(args *GetBlockArgs, reply *string) error { |
||||
err := args.requirements() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
// Do something
|
||||
block := p.ethp.GetBlock(args.Hash) |
||||
*reply = NewSuccessRes(block) |
||||
return nil |
||||
} |
||||
|
||||
type NewTxArgs struct { |
||||
Sec string |
||||
Recipient string |
||||
Value string |
||||
Gas string |
||||
GasPrice string |
||||
Init string |
||||
Body string |
||||
} |
||||
type TxResponse struct { |
||||
Hash string |
||||
} |
||||
|
||||
func (a *NewTxArgs) requirements() error { |
||||
if a.Recipient == "" { |
||||
return NewErrorResponse("Transact requires a 'recipient' address as argument") |
||||
} |
||||
if a.Value == "" { |
||||
return NewErrorResponse("Transact requires a 'value' as argument") |
||||
} |
||||
if a.Gas == "" { |
||||
return NewErrorResponse("Transact requires a 'gas' value as argument") |
||||
} |
||||
if a.GasPrice == "" { |
||||
return NewErrorResponse("Transact requires a 'gasprice' value as argument") |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (a *NewTxArgs) requirementsContract() error { |
||||
if a.Value == "" { |
||||
return NewErrorResponse("Create requires a 'value' as argument") |
||||
} |
||||
if a.Gas == "" { |
||||
return NewErrorResponse("Create requires a 'gas' value as argument") |
||||
} |
||||
if a.GasPrice == "" { |
||||
return NewErrorResponse("Create requires a 'gasprice' value as argument") |
||||
} |
||||
if a.Body == "" { |
||||
return NewErrorResponse("Create requires a 'body' value as argument") |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (p *EthereumApi) Transact(args *NewTxArgs, reply *string) error { |
||||
err := args.requirements() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
result, _ := p.ethp.Transact(p.ethp.GetKey().PrivateKey, args.Recipient, args.Value, args.Gas, args.GasPrice, args.Body) |
||||
*reply = NewSuccessRes(result) |
||||
return nil |
||||
} |
||||
|
||||
func (p *EthereumApi) Create(args *NewTxArgs, reply *string) error { |
||||
err := args.requirementsContract() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
result, _ := p.ethp.Create(p.ethp.GetKey().PrivateKey, args.Value, args.Gas, args.GasPrice, args.Init, args.Body) |
||||
*reply = NewSuccessRes(result) |
||||
return nil |
||||
} |
||||
|
||||
func (p *EthereumApi) GetKey(args interface{}, reply *string) error { |
||||
*reply = NewSuccessRes(p.ethp.GetKey()) |
||||
return nil |
||||
} |
||||
|
||||
type GetStorageArgs struct { |
||||
Address string |
||||
Key string |
||||
} |
||||
|
||||
func (a *GetStorageArgs) requirements() error { |
||||
if a.Address == "" { |
||||
return NewErrorResponse("GetStorageAt requires an 'address' value as argument") |
||||
} |
||||
if a.Key == "" { |
||||
return NewErrorResponse("GetStorageAt requires an 'key' value as argument") |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
type GetStorageAtRes struct { |
||||
Key string `json:"key"` |
||||
Value string `json:"value"` |
||||
Address string `json:"address"` |
||||
} |
||||
|
||||
func (p *EthereumApi) GetStorageAt(args *GetStorageArgs, reply *string) error { |
||||
err := args.requirements() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
state := p.ethp.GetStateObject(args.Address) |
||||
value := state.GetStorage(args.Key) |
||||
*reply = NewSuccessRes(GetStorageAtRes{Address: args.Address, Key: args.Key, Value: value}) |
||||
return nil |
||||
} |
||||
|
||||
type GetBalanceArgs struct { |
||||
Address string |
||||
} |
||||
|
||||
func (a *GetBalanceArgs) requirements() error { |
||||
if a.Address == "" { |
||||
return NewErrorResponse("GetBalanceAt requires an 'address' value as argument") |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
type BalanceRes struct { |
||||
Balance string `json:"balance"` |
||||
Address string `json:"address"` |
||||
} |
||||
|
||||
func (p *EthereumApi) GetBalanceAt(args *GetBalanceArgs, reply *string) error { |
||||
err := args.requirements() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
state := p.ethp.GetStateObject(args.Address) |
||||
*reply = NewSuccessRes(BalanceRes{Balance: state.Value(), Address: args.Address}) |
||||
return nil |
||||
} |
||||
|
||||
type TestRes struct { |
||||
JsonResponse `json:"-"` |
||||
Answer int `json:"answer"` |
||||
} |
||||
|
||||
func (p *EthereumApi) Test(args *GetBlockArgs, reply *string) error { |
||||
*reply = NewSuccessRes(TestRes{Answer: 15}) |
||||
return nil |
||||
} |
@ -0,0 +1,62 @@ |
||||
package ethrpc |
||||
|
||||
import ( |
||||
"github.com/ethereum/eth-go/ethpub" |
||||
"github.com/ethereum/eth-go/ethutil" |
||||
"net" |
||||
"net/rpc" |
||||
"net/rpc/jsonrpc" |
||||
) |
||||
|
||||
type JsonRpcServer struct { |
||||
quit chan bool |
||||
listener net.Listener |
||||
ethp *ethpub.PEthereum |
||||
} |
||||
|
||||
func (s *JsonRpcServer) exitHandler() { |
||||
out: |
||||
for { |
||||
select { |
||||
case <-s.quit: |
||||
s.listener.Close() |
||||
break out |
||||
} |
||||
} |
||||
|
||||
ethutil.Config.Log.Infoln("[JSON] Shutdown JSON-RPC server") |
||||
} |
||||
|
||||
func (s *JsonRpcServer) Stop() { |
||||
close(s.quit) |
||||
} |
||||
|
||||
func (s *JsonRpcServer) Start() { |
||||
ethutil.Config.Log.Infoln("[JSON] Starting JSON-RPC server") |
||||
go s.exitHandler() |
||||
rpc.Register(&EthereumApi{ethp: s.ethp}) |
||||
rpc.HandleHTTP() |
||||
|
||||
for { |
||||
conn, err := s.listener.Accept() |
||||
if err != nil { |
||||
ethutil.Config.Log.Infoln("[JSON] Error starting JSON-RPC:", err) |
||||
break |
||||
} |
||||
ethutil.Config.Log.Debugln("[JSON] Incoming request.") |
||||
go jsonrpc.ServeConn(conn) |
||||
} |
||||
} |
||||
|
||||
func NewJsonRpcServer(ethp *ethpub.PEthereum) *JsonRpcServer { |
||||
l, err := net.Listen("tcp", ":30304") |
||||
if err != nil { |
||||
ethutil.Config.Log.Infoln("Error starting JSON-RPC") |
||||
} |
||||
|
||||
return &JsonRpcServer{ |
||||
listener: l, |
||||
quit: make(chan bool), |
||||
ethp: ethp, |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,74 @@ |
||||
package ethutil |
||||
|
||||
import ( |
||||
"testing" |
||||
) |
||||
|
||||
func TestMnDecode(t *testing.T) { |
||||
words := []string{ |
||||
"ink", |
||||
"balance", |
||||
"gain", |
||||
"fear", |
||||
"happen", |
||||
"melt", |
||||
"mom", |
||||
"surface", |
||||
"stir", |
||||
"bottle", |
||||
"unseen", |
||||
"expression", |
||||
"important", |
||||
"curl", |
||||
"grant", |
||||
"fairy", |
||||
"across", |
||||
"back", |
||||
"figure", |
||||
"breast", |
||||
"nobody", |
||||
"scratch", |
||||
"worry", |
||||
"yesterday", |
||||
} |
||||
encode := "c61d43dc5bb7a4e754d111dae8105b6f25356492df5e50ecb33b858d94f8c338" |
||||
result := MnemonicDecode(words) |
||||
if encode != result { |
||||
t.Error("We expected", encode, "got", result, "instead") |
||||
} |
||||
} |
||||
func TestMnEncode(t *testing.T) { |
||||
encode := "c61d43dc5bb7a4e754d111dae8105b6f25356492df5e50ecb33b858d94f8c338" |
||||
result := []string{ |
||||
"ink", |
||||
"balance", |
||||
"gain", |
||||
"fear", |
||||
"happen", |
||||
"melt", |
||||
"mom", |
||||
"surface", |
||||
"stir", |
||||
"bottle", |
||||
"unseen", |
||||
"expression", |
||||
"important", |
||||
"curl", |
||||
"grant", |
||||
"fairy", |
||||
"across", |
||||
"back", |
||||
"figure", |
||||
"breast", |
||||
"nobody", |
||||
"scratch", |
||||
"worry", |
||||
"yesterday", |
||||
} |
||||
words := MnemonicEncode(encode) |
||||
for i, word := range words { |
||||
if word != result[i] { |
||||
t.Error("Mnenonic does not match:", words, result) |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,123 @@ |
||||
package ethutil |
||||
|
||||
import ( |
||||
"archive/zip" |
||||
"encoding/json" |
||||
"fmt" |
||||
"io" |
||||
"io/ioutil" |
||||
"strings" |
||||
) |
||||
|
||||
// Manifest object
|
||||
//
|
||||
// The manifest object holds all the relevant information supplied with the
|
||||
// the manifest specified in the package
|
||||
type Manifest struct { |
||||
Entry string |
||||
Height, Width int |
||||
} |
||||
|
||||
// External package
|
||||
//
|
||||
// External package contains the main html file and manifest
|
||||
type ExtPackage struct { |
||||
EntryHtml string |
||||
Manifest *Manifest |
||||
} |
||||
|
||||
// Read file
|
||||
//
|
||||
// Read a given compressed file and returns the read bytes.
|
||||
// Returns an error otherwise
|
||||
func ReadFile(f *zip.File) ([]byte, error) { |
||||
rc, err := f.Open() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
defer rc.Close() |
||||
|
||||
content, err := ioutil.ReadAll(rc) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
return content, nil |
||||
} |
||||
|
||||
// Reads manifest
|
||||
//
|
||||
// Reads and returns a manifest object. Returns error otherwise
|
||||
func ReadManifest(m []byte) (*Manifest, error) { |
||||
var manifest Manifest |
||||
|
||||
dec := json.NewDecoder(strings.NewReader(string(m))) |
||||
if err := dec.Decode(&manifest); err == io.EOF { |
||||
} else if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
return &manifest, nil |
||||
} |
||||
|
||||
// Find file in archive
|
||||
//
|
||||
// Returns the index of the given file name if it exists. -1 if file not found
|
||||
func FindFileInArchive(fn string, files []*zip.File) (index int) { |
||||
index = -1 |
||||
// Find the manifest first
|
||||
for i, f := range files { |
||||
if f.Name == fn { |
||||
index = i |
||||
} |
||||
} |
||||
|
||||
return |
||||
} |
||||
|
||||
// Open package
|
||||
//
|
||||
// Opens a prepared ethereum package
|
||||
// Reads the manifest file and determines file contents and returns and
|
||||
// the external package.
|
||||
func OpenPackage(fn string) (*ExtPackage, error) { |
||||
r, err := zip.OpenReader(fn) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
defer r.Close() |
||||
|
||||
manifestIndex := FindFileInArchive("manifest.json", r.File) |
||||
|
||||
if manifestIndex < 0 { |
||||
return nil, fmt.Errorf("No manifest file found in archive") |
||||
} |
||||
|
||||
f, err := ReadFile(r.File[manifestIndex]) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
manifest, err := ReadManifest(f) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
if manifest.Entry == "" { |
||||
return nil, fmt.Errorf("Entry file specified but appears to be empty: %s", manifest.Entry) |
||||
} |
||||
|
||||
entryIndex := FindFileInArchive(manifest.Entry, r.File) |
||||
if entryIndex < 0 { |
||||
return nil, fmt.Errorf("Entry file not found: '%s'", manifest.Entry) |
||||
} |
||||
|
||||
f, err = ReadFile(r.File[entryIndex]) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
extPackage := &ExtPackage{string(f), manifest} |
||||
|
||||
return extPackage, nil |
||||
} |
@ -1,144 +0,0 @@ |
||||
package ethutil |
||||
|
||||
import ( |
||||
"math/big" |
||||
"strconv" |
||||
) |
||||
|
||||
// Op codes
|
||||
var OpCodes = map[string]byte{ |
||||
// 0x0 range - arithmetic ops
|
||||
"STOP": 0x00, |
||||
"ADD": 0x01, |
||||
"MUL": 0x02, |
||||
"SUB": 0x03, |
||||
"DIV": 0x04, |
||||
"SDIV": 0x05, |
||||
"MOD": 0x06, |
||||
"SMOD": 0x07, |
||||
"EXP": 0x08, |
||||
"NEG": 0x09, |
||||
"LT": 0x0a, |
||||
"GT": 0x0b, |
||||
"EQ": 0x0c, |
||||
"NOT": 0x0d, |
||||
|
||||
// 0x10 range - bit ops
|
||||
"AND": 0x10, |
||||
"OR": 0x11, |
||||
"XOR": 0x12, |
||||
"BYTE": 0x13, |
||||
|
||||
// 0x20 range - crypto
|
||||
"SHA3": 0x20, |
||||
|
||||
// 0x30 range - closure state
|
||||
"ADDRESS": 0x30, |
||||
"BALANCE": 0x31, |
||||
"ORIGIN": 0x32, |
||||
"CALLER": 0x33, |
||||
"CALLVALUE": 0x34, |
||||
"CALLDATA": 0x35, |
||||
"CALLDATASIZE": 0x36, |
||||
"GASPRICE": 0x38, |
||||
|
||||
// 0x40 range - block operations
|
||||
"PREVHASH": 0x40, |
||||
"COINBASE": 0x41, |
||||
"TIMESTAMP": 0x42, |
||||
"NUMBER": 0x43, |
||||
"DIFFICULTY": 0x44, |
||||
"GASLIMIT": 0x45, |
||||
|
||||
// 0x50 range - 'storage' and execution
|
||||
"PUSH": 0x50, |
||||
"POP": 0x51, |
||||
"DUP": 0x52, |
||||
"SWAP": 0x53, |
||||
"MLOAD": 0x54, |
||||
"MSTORE": 0x55, |
||||
"MSTORE8": 0x56, |
||||
"SLOAD": 0x57, |
||||
"SSTORE": 0x58, |
||||
"JUMP": 0x59, |
||||
"JUMPI": 0x5a, |
||||
"PC": 0x5b, |
||||
"MSIZE": 0x5c, |
||||
|
||||
// 0x60 range - closures
|
||||
"CREATE": 0x60, |
||||
"CALL": 0x61, |
||||
"RETURN": 0x62, |
||||
|
||||
// 0x70 range - other
|
||||
"LOG": 0x70, |
||||
"SUICIDE": 0x7f, |
||||
} |
||||
|
||||
func IsOpCode(s string) bool { |
||||
for key, _ := range OpCodes { |
||||
if key == s { |
||||
return true |
||||
} |
||||
} |
||||
return false |
||||
} |
||||
|
||||
func CompileInstr(s interface{}) ([]byte, error) { |
||||
switch s.(type) { |
||||
case string: |
||||
str := s.(string) |
||||
isOp := IsOpCode(str) |
||||
if isOp { |
||||
return []byte{OpCodes[str]}, nil |
||||
} |
||||
|
||||
num := new(big.Int) |
||||
_, success := num.SetString(str, 0) |
||||
// Assume regular bytes during compilation
|
||||
if !success { |
||||
num.SetBytes([]byte(str)) |
||||
} |
||||
|
||||
return num.Bytes(), nil |
||||
case int: |
||||
return big.NewInt(int64(s.(int))).Bytes(), nil |
||||
case []byte: |
||||
return BigD(s.([]byte)).Bytes(), nil |
||||
} |
||||
|
||||
return nil, nil |
||||
} |
||||
|
||||
func Instr(instr string) (int, []string, error) { |
||||
|
||||
base := new(big.Int) |
||||
base.SetString(instr, 0) |
||||
|
||||
args := make([]string, 7) |
||||
for i := 0; i < 7; i++ { |
||||
// int(int(val) / int(math.Pow(256,float64(i)))) % 256
|
||||
exp := BigPow(256, i) |
||||
num := new(big.Int) |
||||
num.Div(base, exp) |
||||
|
||||
args[i] = num.Mod(num, big.NewInt(256)).String() |
||||
} |
||||
op, _ := strconv.Atoi(args[0]) |
||||
|
||||
return op, args[1:7], nil |
||||
} |
||||
|
||||
// Script compilation functions
|
||||
// Compiles strings to machine code
|
||||
func Compile(instructions ...interface{}) (script []string) { |
||||
script = make([]string, len(instructions)) |
||||
|
||||
for i, val := range instructions { |
||||
instr, _ := CompileInstr(val) |
||||
|
||||
script[i] = string(instr) |
||||
} |
||||
|
||||
return |
||||
} |
@ -1,32 +0,0 @@ |
||||
package ethutil |
||||
|
||||
/* |
||||
import ( |
||||
"math" |
||||
"testing" |
||||
) |
||||
|
||||
func TestCompile(t *testing.T) { |
||||
instr, err := CompileInstr("PUSH") |
||||
|
||||
if err != nil { |
||||
t.Error("Failed compiling instruction") |
||||
} |
||||
|
||||
calc := (48 + 0*256 + 0*int64(math.Pow(256, 2))) |
||||
if BigD(instr).Int64() != calc { |
||||
t.Error("Expected", calc, ", got:", instr) |
||||
} |
||||
} |
||||
|
||||
func TestValidInstr(t *testing.T) { |
||||
op, args, err := Instr("68163") |
||||
if err != nil { |
||||
t.Error("Error decoding instruction") |
||||
} |
||||
|
||||
} |
||||
|
||||
func TestInvalidInstr(t *testing.T) { |
||||
} |
||||
*/ |
@ -0,0 +1,41 @@ |
||||
package ethutil |
||||
|
||||
import ( |
||||
"fmt" |
||||
"github.com/obscuren/mutan" |
||||
"strings" |
||||
) |
||||
|
||||
// General compile function
|
||||
func Compile(script string) ([]byte, error) { |
||||
byteCode, errors := mutan.Compile(strings.NewReader(script), false) |
||||
if len(errors) > 0 { |
||||
var errs string |
||||
for _, er := range errors { |
||||
if er != nil { |
||||
errs += er.Error() |
||||
} |
||||
} |
||||
return nil, fmt.Errorf("%v", errs) |
||||
} |
||||
|
||||
return byteCode, nil |
||||
} |
||||
|
||||
func CompileScript(script string) ([]byte, []byte, error) { |
||||
// Preprocess
|
||||
mainInput, initInput := mutan.PreProcess(script) |
||||
// Compile main script
|
||||
mainScript, err := Compile(mainInput) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
|
||||
// Compile init script
|
||||
initScript, err := Compile(initInput) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
|
||||
return mainScript, initScript, nil |
||||
} |
Loading…
Reference in new issue