Exemple #1
0
// genValueTx returns a block generator that includes a single
// value-transfer transaction with n bytes of extra data in each
// block.
func genValueTx(nbytes int) func(int, *BlockGen) {
	return func(i int, gen *BlockGen) {
		toaddr := common.Address{}
		data := make([]byte, nbytes)
		gas := IntrinsicGas(data)
		tx, _ := types.NewTransaction(gen.TxNonce(benchRootAddr), toaddr, big.NewInt(1), gas, nil, data).SignECDSA(benchRootKey)
		gen.AddTx(tx)
	}
}
func TestNegativeValue(t *testing.T) {
	pool, key := setupTxPool()

	tx, _ := types.NewTransaction(0, common.Address{}, big.NewInt(-1), big.NewInt(100), big.NewInt(1), nil).SignECDSA(key)
	from, _ := tx.From()
	pool.currentState().AddBalance(from, big.NewInt(1))
	if err := pool.Add(tx, false); err != ErrNegativeValue {
		t.Error("expected", ErrNegativeValue, "got", err)
	}
}
Exemple #3
0
// genTxRing returns a block generator that sends ether in a ring
// among n accounts. This is creates n entries in the state database
// and fills the blocks with many small transactions.
func genTxRing(naccounts int) func(int, *BlockGen) {
	from := 0
	return func(i int, gen *BlockGen) {
		gas := CalcGasLimit(gen.PrevBlock(i - 1))
		for {
			gas.Sub(gas, params.TxGas)
			if gas.Cmp(params.TxGas) < 0 {
				break
			}
			to := (from + 1) % naccounts
			tx := types.NewTransaction(
				gen.TxNonce(ringAddrs[from]),
				ringAddrs[to],
				benchRootFunds,
				params.TxGas,
				nil,
				nil,
			)
			tx, _ = tx.SignECDSA(ringKeys[from])
			gen.AddTx(tx)
			from = to
		}
	}
}
Exemple #4
0
func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) {

	// this minimalistic recoding is enough (works for natspec.js)
	var jsontx = fmt.Sprintf(`{"params":[{"to":"%s","data": "%s"}]}`, toStr, codeStr)
	if !self.ConfirmTransaction(jsontx) {
		err := fmt.Errorf("Transaction not confirmed")
		return "", err
	}

	if len(toStr) > 0 && toStr != "0x" && !isAddress(toStr) {
		return "", errors.New("Invalid address")
	}

	var (
		from             = common.HexToAddress(fromStr)
		to               = common.HexToAddress(toStr)
		value            = common.Big(valueStr)
		gas              *big.Int
		price            *big.Int
		data             []byte
		contractCreation bool
	)

	if len(gasStr) == 0 {
		gas = DefaultGas()
	} else {
		gas = common.Big(gasStr)
	}

	if len(gasPriceStr) == 0 {
		price = self.DefaultGasPrice()
	} else {
		price = common.Big(gasPriceStr)
	}

	data = common.FromHex(codeStr)
	if len(toStr) == 0 {
		contractCreation = true
	}

	if gas.Cmp(big.NewInt(90000)) < 0 {
		glog.Infof("(Gas set to %v for hash: %x. Miners can ignore transactions with a low amount of gas.", gas, toStr)
	}

	// 2015-05-18 Is this still needed?
	// TODO if no_private_key then
	//if _, exists := p.register[args.From]; exists {
	//	p.register[args.From] = append(p.register[args.From], args)
	//} else {
	/*
		account := accounts.Get(common.FromHex(args.From))
		if account != nil {
			if account.Unlocked() {
				if !unlockAccount(account) {
					return
				}
			}

			result, _ := account.Transact(common.FromHex(args.To), common.FromHex(args.Value), common.FromHex(args.Gas), common.FromHex(args.GasPrice), common.FromHex(args.Data))
			if len(result) > 0 {
				*reply = common.ToHex(result)
			}
		} else if _, exists := p.register[args.From]; exists {
			p.register[ags.From] = append(p.register[args.From], args)
		}
	*/

	self.transactMu.Lock()
	defer self.transactMu.Unlock()

	var nonce uint64
	if len(nonceStr) != 0 {
		nonce = common.Big(nonceStr).Uint64()
	} else {
		state := self.backend.TxPool().State()
		nonce = state.GetNonce(from)
	}
	var tx *types.Transaction
	if contractCreation {
		tx = types.NewContractCreation(nonce, value, gas, price, data)
	} else {
		tx = types.NewTransaction(nonce, to, value, gas, price, data)
	}

	signed, err := self.sign(tx, from, false)
	if err != nil {
		return "", err
	}
	if err = self.backend.TxPool().Add(signed, true); err != nil {
		return "", err
	}

	if contractCreation {
		addr := crypto.CreateAddress(from, nonce)
		glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signed.Hash().Hex(), addr.Hex())
	} else {
		glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signed.Hash().Hex(), tx.To().Hex())
	}

	return signed.Hash().Hex(), nil
}
Exemple #5
0
func newtx(from *crypto.Key, nonce uint64, datasize int) *types.Transaction {
	data := make([]byte, datasize)
	tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), data)
	tx, _ = tx.SignECDSA(from.PrivateKey)
	return tx
}
func transaction(nonce uint64, gaslimit *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
	tx, _ := types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, big.NewInt(1), nil).SignECDSA(key)
	return tx
}
Exemple #7
0
func ExampleGenerateChain() {
	params.MinGasLimit = big.NewInt(125000)      // Minimum the gas limit may ever be.
	params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.

	var (
		key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
		key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
		key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
		addr1   = crypto.PubkeyToAddress(key1.PublicKey)
		addr2   = crypto.PubkeyToAddress(key2.PublicKey)
		addr3   = crypto.PubkeyToAddress(key3.PublicKey)
		db, _   = ethdb.NewMemDatabase()
	)

	// Ensure that key1 has some funds in the genesis block.
	genesis := WriteGenesisBlockForTesting(db, addr1, big.NewInt(1000000))

	// This call generates a chain of 5 blocks. The function runs for
	// each block and adds different features to gen based on the
	// block index.
	chain := GenerateChain(genesis, db, 5, func(i int, gen *BlockGen) {
		switch i {
		case 0:
			// In block 1, addr1 sends addr2 some ether.
			tx, _ := types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(key1)
			gen.AddTx(tx)
		case 1:
			// In block 2, addr1 sends some more ether to addr2.
			// addr2 passes it on to addr3.
			tx1, _ := types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
			tx2, _ := types.NewTransaction(gen.TxNonce(addr2), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
			gen.AddTx(tx1)
			gen.AddTx(tx2)
		case 2:
			// Block 3 is empty but was mined by addr3.
			gen.SetCoinbase(addr3)
			gen.SetExtra([]byte("yeehaw"))
		case 3:
			// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
			b2 := gen.PrevBlock(1).Header()
			b2.Extra = []byte("foo")
			gen.AddUncle(b2)
			b3 := gen.PrevBlock(2).Header()
			b3.Extra = []byte("foo")
			gen.AddUncle(b3)
		}
	})

	// Import the chain. This runs all block validation rules.
	evmux := &event.TypeMux{}
	chainman, _ := NewChainManager(db, FakePow{}, evmux)
	chainman.SetProcessor(NewBlockProcessor(db, FakePow{}, chainman, evmux))
	if i, err := chainman.InsertChain(chain); err != nil {
		fmt.Printf("insert error (block %d): %v\n", i, err)
		return
	}

	state := chainman.State()
	fmt.Printf("last block: #%d\n", chainman.CurrentBlock().Number())
	fmt.Println("balance of addr1:", state.GetBalance(addr1))
	fmt.Println("balance of addr2:", state.GetBalance(addr2))
	fmt.Println("balance of addr3:", state.GetBalance(addr3))
	// Output:
	// last block: #5
	// balance of addr1: 989000
	// balance of addr2: 10000
	// balance of addr3: 19687500000000001000
}
Exemple #8
0
func (tx *tx) UnmarshalJSON(b []byte) (err error) {
	var fields map[string]interface{}
	if err := json.Unmarshal(b, &fields); err != nil {
		return shared.NewDecodeParamError(err.Error())
	}

	var (
		nonce            uint64
		to               common.Address
		amount           = new(big.Int).Set(common.Big0)
		gasLimit         = new(big.Int).Set(common.Big0)
		gasPrice         = new(big.Int).Set(common.Big0)
		data             []byte
		contractCreation = true
	)

	if val, found := fields["Hash"]; found {
		if hashVal, ok := val.(string); ok {
			tx.Hash = hashVal
		}
	}

	if val, found := fields["To"]; found {
		if strVal, ok := val.(string); ok && len(strVal) > 0 {
			tx.To = strVal
			to = common.HexToAddress(strVal)
			contractCreation = false
		}
	}

	if val, found := fields["From"]; found {
		if strVal, ok := val.(string); ok {
			tx.From = strVal
		}
	}

	if val, found := fields["Nonce"]; found {
		if strVal, ok := val.(string); ok {
			tx.Nonce = strVal
			if nonce, err = strconv.ParseUint(strVal, 10, 64); err != nil {
				return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.Nonce - %v", err))
			}
		}
	} else {
		return shared.NewDecodeParamError("tx.Nonce not found")
	}

	var parseOk bool
	if val, found := fields["Value"]; found {
		if strVal, ok := val.(string); ok {
			tx.Value = strVal
			if _, parseOk = amount.SetString(strVal, 0); !parseOk {
				return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.Amount - %v", err))
			}
		}
	}

	if val, found := fields["Data"]; found {
		if strVal, ok := val.(string); ok {
			tx.Data = strVal
			if strings.HasPrefix(strVal, "0x") {
				data = common.Hex2Bytes(strVal[2:])
			} else {
				data = common.Hex2Bytes(strVal)
			}
		}
	}

	if val, found := fields["GasLimit"]; found {
		if strVal, ok := val.(string); ok {
			tx.GasLimit = strVal
			if _, parseOk = gasLimit.SetString(strVal, 0); !parseOk {
				return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.GasLimit - %v", err))
			}
		}
	}

	if val, found := fields["GasPrice"]; found {
		if strVal, ok := val.(string); ok {
			tx.GasPrice = strVal
			if _, parseOk = gasPrice.SetString(strVal, 0); !parseOk {
				return shared.NewDecodeParamError(fmt.Sprintf("Unable to decode tx.GasPrice - %v", err))
			}
		}
	}

	if contractCreation {
		tx.tx = types.NewContractCreation(nonce, amount, gasLimit, gasPrice, data)
	} else {
		tx.tx = types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data)
	}

	return nil
}