This commit is contained in:
Zach 2017-06-21 07:54:53 +00:00 committed by GitHub
commit 36157535a8
92 changed files with 126 additions and 639 deletions

View file

@ -8,6 +8,11 @@
.PHONY: geth-darwin geth-darwin-386 geth-darwin-amd64 .PHONY: geth-darwin geth-darwin-386 geth-darwin-amd64
.PHONY: geth-windows geth-windows-386 geth-windows-amd64 .PHONY: geth-windows geth-windows-386 geth-windows-amd64
PACKAGES=$(shell go list ./... | grep -v '/vendor/')
megacheck:
@for pkg in ${PACKAGES}; do megacheck "$$pkg"; done
GOBIN = build/bin GOBIN = build/bin
GO ?= latest GO ?= latest

View file

@ -91,14 +91,6 @@ type cipherparamsJSON struct {
IV string `json:"iv"` IV string `json:"iv"`
} }
type scryptParamsJSON struct {
N int `json:"n"`
R int `json:"r"`
P int `json:"p"`
DkLen int `json:"dklen"`
Salt string `json:"salt"`
}
func (k *Key) MarshalJSON() (j []byte, err error) { func (k *Key) MarshalJSON() (j []byte, err error) {
jStruct := plainKeyJSON{ jStruct := plainKeyJSON{
hex.EncodeToString(k.Address[:]), hex.EncodeToString(k.Address[:]),

View file

@ -45,8 +45,6 @@ import (
) )
const ( const (
keyHeaderKDF = "scrypt"
// StandardScryptN is the N parameter of Scrypt encryption algorithm, using 256MB // StandardScryptN is the N parameter of Scrypt encryption algorithm, using 256MB
// memory and taking approximately 1s CPU time on a modern processor. // memory and taking approximately 1s CPU time on a modern processor.
StandardScryptN = 1 << 18 StandardScryptN = 1 << 18

View file

@ -199,7 +199,7 @@ func (hub *LedgerHub) updater() {
for { for {
// Wait for a USB hotplug event (not supported yet) or a refresh timeout // Wait for a USB hotplug event (not supported yet) or a refresh timeout
select { select {
//case <-hub.changes: // reenable on hutplug implementation // case <-hub.changes: // re-enable on hutplug implementation
case <-time.After(ledgerRefreshCycle): case <-time.After(ledgerRefreshCycle):
} }
// Run the wallet refresher // Run the wallet refresher

View file

@ -65,11 +65,9 @@ const (
ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration
ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet
ledgerP1ConfirmFetchAddress ledgerParam1 = 0x01 // Require a user confirmation before returning the address
ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing
ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing
ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
ledgerP2ReturnAddressChainCode ledgerParam2 = 0x01 // Require a user confirmation before returning the address
) )
// errReplyInvalidHeader is the error message returned by a Ledger data exchange // errReplyInvalidHeader is the error message returned by a Ledger data exchange

View file

@ -46,8 +46,6 @@ func disasmCmd(ctx *cli.Context) error {
code := strings.TrimSpace(string(in[:])) code := strings.TrimSpace(string(in[:]))
fmt.Printf("%v\n", code) fmt.Printf("%v\n", code)
if err = asm.PrintDisassembled(code); err != nil {
return err return asm.PrintDisassembled(code)
}
return nil
} }

View file

@ -122,7 +122,7 @@ func dial(server string, pubkey []byte) (*sshClient, error) {
} }
} }
// If a public key exists for this SSH server, check that it matches // If a public key exists for this SSH server, check that it matches
if bytes.Compare(pubkey, key.Marshal()) == 0 { if bytes.Equal(pubkey, key.Marshal()) {
return nil return nil
} }
// We have a mismatch, forbid connecting // We have a mismatch, forbid connecting

View file

@ -121,7 +121,7 @@ func TestCompression(t *testing.T) {
in := hexutil.MustDecode("0x4912385c0e7b64000000") in := hexutil.MustDecode("0x4912385c0e7b64000000")
out := hexutil.MustDecode("0x80fe4912385c0e7b64") out := hexutil.MustDecode("0x80fe4912385c0e7b64")
if data := CompressBytes(in); bytes.Compare(data, out) != 0 { if data := CompressBytes(in); !bytes.Equal(data, out) {
t.Errorf("encoding mismatch for sparse data: have %x, want %x", data, out) t.Errorf("encoding mismatch for sparse data: have %x, want %x", data, out)
} }
if data, err := DecompressBytes(out, len(in)); err != nil || bytes.Compare(data, in) != 0 { if data, err := DecompressBytes(out, len(in)); err != nil || bytes.Compare(data, in) != 0 {

View file

@ -24,10 +24,7 @@ import (
"strconv" "strconv"
) )
var ( var errNonString = errors.New("cannot unmarshal non-string as hex data")
textZero = []byte(`0x0`)
errNonString = errors.New("cannot unmarshal non-string as hex data")
)
// Bytes marshals/unmarshals as a JSON string with 0x prefix. // Bytes marshals/unmarshals as a JSON string with 0x prefix.
// The empty slice marshals as "0x". // The empty slice marshals as "0x".

View file

@ -223,9 +223,9 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) {
// Tally up the new vote from the signer // Tally up the new vote from the signer
var authorize bool var authorize bool
switch { switch {
case bytes.Compare(header.Nonce[:], nonceAuthVote) == 0: case bytes.Equal(header.Nonce[:], nonceAuthVote):
authorize = true authorize = true
case bytes.Compare(header.Nonce[:], nonceDropVote) == 0: case bytes.Equal(header.Nonce[:], nonceDropVote):
authorize = false authorize = false
default: default:
return nil, errInvalidVote return nil, errInvalidVote

View file

@ -77,8 +77,6 @@ type tester struct {
console *Console console *Console
input *hookedPrompter input *hookedPrompter
output *bytes.Buffer output *bytes.Buffer
lastConfirm string
} }
// newTester creates a test environment based on which the console can operate. // newTester creates a test environment based on which the console can operate.

View file

@ -395,7 +395,6 @@ func (self *Chequebook) autoDeposit(interval time.Duration) {
} }
} }
}() }()
return
} }
// Outbox can issue cheques from a single contract to a single beneficiary. // Outbox can issue cheques from a single contract to a single beneficiary.
@ -436,7 +435,6 @@ type Inbox struct {
sender common.Address // local peer's address to send cashing tx from sender common.Address // local peer's address to send cashing tx from
signer *ecdsa.PublicKey // peer's public key signer *ecdsa.PublicKey // peer's public key
txhash string // tx hash of last cashing tx txhash string // tx hash of last cashing tx
abigen bind.ContractBackend // blockchain API
session *contract.ChequebookSession // abi contract backend with tx opts session *contract.ChequebookSession // abi contract backend with tx opts
quit chan bool // when closed causes autocash to stop quit chan bool // when closed causes autocash to stop
maxUncashed *big.Int // threshold that triggers autocashing maxUncashed *big.Int // threshold that triggers autocashing
@ -543,7 +541,6 @@ func (self *Inbox) autoCash(cashInterval time.Duration) {
} }
} }
}() }()
return
} }
// Receive is called to deposit the latest cheque to the incoming Inbox. // Receive is called to deposit the latest cheque to the incoming Inbox.

View file

@ -114,10 +114,7 @@ func PrintDisassembled(code string) error {
fmt.Printf("%06v: %v\n", it.PC(), it.Op()) fmt.Printf("%06v: %v\n", it.PC(), it.Op())
} }
} }
if err := it.Error(); err != nil { return it.Error()
return err
}
return nil
} }
// Return all disassembled EVM instructions in human-readable format. // Return all disassembled EVM instructions in human-readable format.

View file

@ -17,7 +17,6 @@
package asm package asm
import ( import (
"errors"
"fmt" "fmt"
"math/big" "math/big"
"os" "os"
@ -237,10 +236,7 @@ func (c *Compiler) pushBin(v interface{}) {
// isPush returns whether the string op is either any of // isPush returns whether the string op is either any of
// push(N). // push(N).
func isPush(op string) bool { func isPush(op string) bool {
if op == "push" { return op == "push"
return true
}
return false
} }
// isJump returns whether the string op is jump(i) // isJump returns whether the string op is jump(i)
@ -267,11 +263,6 @@ func (err compileError) Error() string {
return fmt.Sprintf("%d syntax error: unexpected %v, expected %v", err.lineno, err.got, err.want) return fmt.Sprintf("%d syntax error: unexpected %v, expected %v", err.lineno, err.got, err.want)
} }
var (
errExpBol = errors.New("expected beginning of line")
errExpElementOrLabel = errors.New("expected beginning of line")
)
func compileErr(c token, got, want string) error { func compileErr(c token, got, want string) error {
return compileError{ return compileError{
got: got, got: got,

View file

@ -145,7 +145,7 @@ func (l *lexer) ignore() {
// Accepts checks whether the given input matches the next rune // Accepts checks whether the given input matches the next rune
func (l *lexer) accept(valid string) bool { func (l *lexer) accept(valid string) bool {
if strings.IndexRune(valid, l.next()) >= 0 { if strings.ContainsRune(valid, l.next()) {
return true return true
} }
@ -157,7 +157,7 @@ func (l *lexer) accept(valid string) bool {
// acceptRun will continue to advance the seeker until valid // acceptRun will continue to advance the seeker until valid
// can no longer be met. // can no longer be met.
func (l *lexer) acceptRun(valid string) { func (l *lexer) acceptRun(valid string) {
for strings.IndexRune(valid, l.next()) >= 0 { for strings.ContainsRune(valid, l.next()) {
} }
l.backup() l.backup()
} }
@ -166,7 +166,7 @@ func (l *lexer) acceptRun(valid string) {
// to advance the seeker until the rune has been found. // to advance the seeker until the rune has been found.
func (l *lexer) acceptRunUntil(until rune) bool { func (l *lexer) acceptRunUntil(until rune) bool {
// Continues running until a rune is found // Continues running until a rune is found
for i := l.next(); strings.IndexRune(string(until), i) == -1; i = l.next() { for i := l.next(); !strings.ContainsRune(string(until), i); i = l.next() {
if i == 0 { if i == 0 {
return false return false
} }

View file

@ -88,7 +88,6 @@ type BlockChain struct {
chainmu sync.RWMutex // blockchain insertion lock chainmu sync.RWMutex // blockchain insertion lock
procmu sync.RWMutex // block processor lock procmu sync.RWMutex // block processor lock
checkpoint int // checkpoint counts towards the new checkpoint
currentBlock *types.Block // Current head of the block chain currentBlock *types.Block // Current head of the block chain
currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!) currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)

View file

@ -17,7 +17,6 @@
package core package core
import ( import (
"fmt"
"math/big" "math/big"
"math/rand" "math/rand"
"testing" "testing"
@ -109,13 +108,6 @@ func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, compara
comparator(tdPre, tdPost) comparator(tdPre, tdPost)
} }
func printChain(bc *BlockChain) {
for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- {
b := bc.GetBlockByNumber(uint64(i))
fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty())
}
}
// testBlockChainImport tries to process a chain of blocks, writing them into // testBlockChainImport tries to process a chain of blocks, writing them into
// the database if successful. // the database if successful.
func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error { func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
@ -171,15 +163,6 @@ func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error
return nil return nil
} }
func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) {
_, err := blockchain.InsertChain(chain)
if err != nil {
fmt.Println(err)
t.FailNow()
}
done <- true
}
func TestLastBlock(t *testing.T) { func TestLastBlock(t *testing.T) {
bchain := newTestBlockChain(false) bchain := newTestBlockChain(false)
block := makeBlockChain(bchain.CurrentBlock(), 1, bchain.chainDb, 0)[0] block := makeBlockChain(bchain.CurrentBlock(), 1, bchain.chainDb, 0)[0]
@ -522,6 +505,11 @@ func testInsertNonceError(t *testing.T, full bool) {
blockchain.engine = ethash.NewFakeFailer(failNum) blockchain.engine = ethash.NewFakeFailer(failNum)
failRes, err = blockchain.InsertChain(blocks) failRes, err = blockchain.InsertChain(blocks)
// catching this error fails the test
//if err != nil {
// t.Fatalf("failed to insert chain: %v", err)
//}
} else { } else {
headers := makeHeaderChain(blockchain.CurrentHeader(), i, db, 0) headers := makeHeaderChain(blockchain.CurrentHeader(), i, db, 0)
@ -531,6 +519,10 @@ func testInsertNonceError(t *testing.T, full bool) {
blockchain.engine = ethash.NewFakeFailer(failNum) blockchain.engine = ethash.NewFakeFailer(failNum)
blockchain.hc.engine = blockchain.engine blockchain.hc.engine = blockchain.engine
failRes, err = blockchain.InsertHeaderChain(headers, 1) failRes, err = blockchain.InsertHeaderChain(headers, 1)
// catching this error fails the test
//if err != nil {
// t.Fatalf("failed to insert header chain: %v", err)
//}
} }
// Check that the returned error indicates the failure. // Check that the returned error indicates the failure.
if failRes != failAt { if failRes != failAt {

View file

@ -62,7 +62,6 @@ var (
oldBodySuffix = []byte("-body") oldBodySuffix = []byte("-body")
oldBlockNumPrefix = []byte("block-num-") oldBlockNumPrefix = []byte("block-num-")
oldBlockReceiptsPrefix = []byte("receipts-block-") oldBlockReceiptsPrefix = []byte("receipts-block-")
oldBlockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually]
ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error

View file

@ -24,7 +24,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
@ -64,21 +63,6 @@ type GenesisAccount struct {
Nonce uint64 `json:"nonce,omitempty"` Nonce uint64 `json:"nonce,omitempty"`
} }
// field type overrides for gencodec
type genesisSpecMarshaling struct {
Nonce math.HexOrDecimal64
Timestamp math.HexOrDecimal64
ExtraData hexutil.Bytes
GasLimit math.HexOrDecimal64
Difficulty *math.HexOrDecimal256
Alloc map[common.UnprefixedAddress]GenesisAccount
}
type genesisAccountMarshaling struct {
Code hexutil.Bytes
Balance *math.HexOrDecimal256
Nonce math.HexOrDecimal64
}
// GenesisMismatchError is raised when trying to overwrite an existing // GenesisMismatchError is raised when trying to overwrite an existing
// genesis block with an incompatible one. // genesis block with an incompatible one.
type GenesisMismatchError struct { type GenesisMismatchError struct {

View file

@ -18,7 +18,6 @@ package core
import ( import (
"container/list" "container/list"
"fmt"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
@ -75,20 +74,3 @@ func (tm *TestManager) EventMux() *event.TypeMux {
func (tm *TestManager) Db() ethdb.Database { func (tm *TestManager) Db() ethdb.Database {
return tm.db return tm.db
} }
func NewTestManager() *TestManager {
db, err := ethdb.NewMemDatabase()
if err != nil {
fmt.Println("Could not create mem-db, failing")
return nil
}
testManager := &TestManager{}
testManager.eventMux = new(event.TypeMux)
testManager.db = db
// testManager.txPool = NewTxPool(testManager)
// testManager.blockChain = NewBlockChain(testManager)
// testManager.stateManager = NewStateManager(testManager)
return testManager
}

View file

@ -85,17 +85,6 @@ type Header struct {
Nonce BlockNonce `json:"nonce" gencodec:"required"` Nonce BlockNonce `json:"nonce" gencodec:"required"`
} }
// field type overrides for gencodec
type headerMarshaling struct {
Difficulty *hexutil.Big
Number *hexutil.Big
GasLimit *hexutil.Big
GasUsed *hexutil.Big
Time *hexutil.Big
Extra hexutil.Bytes
Hash common.Hash `json:"hash"` // adds call to Hash() in MarshalJSON
}
// Hash returns the block hash of the header, which is simply the keccak256 hash of its // Hash returns the block hash of the header, which is simply the keccak256 hash of its
// RLP encoding. // RLP encoding.
func (h *Header) Hash() common.Hash { func (h *Header) Hash() common.Hash {

View file

@ -21,7 +21,6 @@ import (
"io" "io"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
@ -56,13 +55,6 @@ type Log struct {
Removed bool `json:"removed"` Removed bool `json:"removed"`
} }
type logMarshaling struct {
Data hexutil.Bytes
BlockNumber hexutil.Uint64
TxIndex hexutil.Uint
Index hexutil.Uint
}
type rlpLog struct { type rlpLog struct {
Address common.Address Address common.Address
Topics []common.Hash Topics []common.Hash

View file

@ -22,7 +22,6 @@ import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
@ -42,12 +41,6 @@ type Receipt struct {
GasUsed *big.Int `json:"gasUsed" gencodec:"required"` GasUsed *big.Int `json:"gasUsed" gencodec:"required"`
} }
type receiptMarshaling struct {
PostState hexutil.Bytes
CumulativeGasUsed *hexutil.Big
GasUsed *hexutil.Big
}
// NewReceipt creates a barebone transaction receipt, copying the init fields. // NewReceipt creates a barebone transaction receipt, copying the init fields.
func NewReceipt(root []byte, cumulativeGasUsed *big.Int) *Receipt { func NewReceipt(root []byte, cumulativeGasUsed *big.Int) *Receipt {
return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)} return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)}

View file

@ -25,17 +25,13 @@ import (
"sync/atomic" "sync/atomic"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
//go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go //go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go
var ( var ErrInvalidSig = errors.New("invalid transaction v, r, s values")
ErrInvalidSig = errors.New("invalid transaction v, r, s values")
errNoSigner = errors.New("missing signing methods")
)
// deriveSigner makes a *best* guess about which signer to use. // deriveSigner makes a *best* guess about which signer to use.
func deriveSigner(V *big.Int) Signer { func deriveSigner(V *big.Int) Signer {
@ -71,17 +67,6 @@ type txdata struct {
Hash *common.Hash `json:"hash" rlp:"-"` Hash *common.Hash `json:"hash" rlp:"-"`
} }
type txdataMarshaling struct {
AccountNonce hexutil.Uint64
Price *hexutil.Big
GasLimit *hexutil.Big
Amount *hexutil.Big
Payload hexutil.Bytes
V *hexutil.Big
R *hexutil.Big
S *hexutil.Big
}
func NewTransaction(nonce uint64, to common.Address, amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction { func NewTransaction(nonce uint64, to common.Address, amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction {
return newTransaction(nonce, &to, amount, gasLimit, gasPrice, data) return newTransaction(nonce, &to, amount, gasLimit, gasPrice, data)
} }

View file

@ -27,12 +27,7 @@ import (
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
) )
var ( var ErrInvalidChainId = errors.New("invalid chaid id for signer")
ErrInvalidChainId = errors.New("invalid chaid id for signer")
errAbstractSigner = errors.New("abstract signer")
abstractSignerAddress = common.HexToAddress("ffffffffffffffffffffffffffffffffffffffff")
)
// sigCache is used to cache the derived sender and contains // sigCache is used to cache the derived sender and contains
// the signer used to derive it. // the signer used to derive it.

View file

@ -18,7 +18,6 @@ package vm
import ( import (
"crypto/sha256" "crypto/sha256"
"errors"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -28,8 +27,6 @@ import (
"golang.org/x/crypto/ripemd160" "golang.org/x/crypto/ripemd160"
) )
var errBadPrecompileInput = errors.New("bad pre compile input")
// Precompiled contract is the basic interface for native Go contracts. The implementation // Precompiled contract is the basic interface for native Go contracts. The implementation
// requires a deterministic gas count based on the input size of the Run method of the // requires a deterministic gas count based on the input size of the Run method of the
// contract. // contract.

View file

@ -60,8 +60,6 @@ type Interpreter struct {
cfg Config cfg Config
gasTable params.GasTable gasTable params.GasTable
intPool *intPool intPool *intPool
readonly bool
} }
// NewInterpreter returns a new instance of the Interpreter. // NewInterpreter returns a new instance of the Interpreter.

View file

@ -51,8 +51,6 @@ type operation struct {
writes bool writes bool
// valid is used to check whether the retrieved operation is valid and known // valid is used to check whether the retrieved operation is valid and known
valid bool valid bool
// reverts determined whether the operation reverts state
reverts bool
} }
var ( var (

View file

@ -24,7 +24,6 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
) )
@ -65,16 +64,6 @@ type StructLog struct {
Err error `json:"error"` Err error `json:"error"`
} }
// overrides for gencodec
type structLogMarshaling struct {
Stack []*math.HexOrDecimal256
Gas math.HexOrDecimal64
GasCost math.HexOrDecimal64
Memory hexutil.Bytes
OpName string `json:"opName"`
MemorySize int `json:"memSize"`
}
func (s *StructLog) OpName() string { func (s *StructLog) OpName() string {
return s.Op.String() return s.Op.String()
} }

View file

@ -61,12 +61,6 @@ func memoryCall(stack *Stack) *big.Int {
return math.BigMax(x, y) return math.BigMax(x, y)
} }
func memoryCallCode(stack *Stack) *big.Int {
x := calcMemSize(stack.Back(5), stack.Back(6))
y := calcMemSize(stack.Back(3), stack.Back(4))
return math.BigMax(x, y)
}
func memoryDelegateCall(stack *Stack) *big.Int { func memoryDelegateCall(stack *Stack) *big.Int {
x := calcMemSize(stack.Back(4), stack.Back(5)) x := calcMemSize(stack.Back(4), stack.Back(5))
y := calcMemSize(stack.Back(2), stack.Back(3)) y := calcMemSize(stack.Back(2), stack.Back(3))

View file

@ -158,7 +158,6 @@ func incCounter(ctr []byte) {
} else if ctr[0]++; ctr[0] != 0 { } else if ctr[0]++; ctr[0] != 0 {
return return
} }
return
} }
// NIST SP 800-56 Concatenation Key Derivation Function (see section 5.8.1). // NIST SP 800-56 Concatenation Key Derivation Function (see section 5.8.1).

View file

@ -71,19 +71,6 @@ func TestKDF(t *testing.T) {
var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match") var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match")
// cmpParams compares a set of ECIES parameters. We assume, as per the
// docs, that AES is the only supported symmetric encryption algorithm.
func cmpParams(p1, p2 *ECIESParams) bool {
if p1.hashAlgo != p2.hashAlgo {
return false
} else if p1.KeyLen != p2.KeyLen {
return false
} else if p1.BlockSize != p2.BlockSize {
return false
}
return true
}
// cmpPublic returns true if the two public keys represent the same pojnt. // cmpPublic returns true if the two public keys represent the same pojnt.
func cmpPublic(pub1, pub2 PublicKey) bool { func cmpPublic(pub1, pub2 PublicKey) bool {
if pub1.X == nil || pub1.Y == nil { if pub1.X == nil || pub1.Y == nil {

View file

@ -42,9 +42,8 @@ type state struct {
storage [maxRate]byte storage [maxRate]byte
// Specific to SHA-3 and SHAKE. // Specific to SHA-3 and SHAKE.
fixedOutput bool // whether this is a fixed-output-length instance outputLen int // the default output size in bytes
outputLen int // the default output size in bytes state spongeDirection // whether the sponge is absorbing or squeezing
state spongeDirection // whether the sponge is absorbing or squeezing
} }
// BlockSize returns the rate of sponge underlying this hash function. // BlockSize returns the rate of sponge underlying this hash function.

View file

@ -53,15 +53,6 @@ var testShakes = map[string]func() ShakeHash{
"SHAKE256": NewShake256, "SHAKE256": NewShake256,
} }
// decodeHex converts a hex-encoded string into a raw byte string.
func decodeHex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}
// structs used to marshal JSON test-cases. // structs used to marshal JSON test-cases.
type KeccakKats struct { type KeccakKats struct {
Kats map[string][]struct { Kats map[string][]struct {
@ -123,37 +114,6 @@ func TestKeccakKats(t *testing.T) {
}) })
} }
// TestUnalignedWrite tests that writing data in an arbitrary pattern with
// small input buffers.
func testUnalignedWrite(t *testing.T) {
testUnalignedAndGeneric(t, func(impl string) {
buf := sequentialBytes(0x10000)
for alg, df := range testDigests {
d := df()
d.Reset()
d.Write(buf)
want := d.Sum(nil)
d.Reset()
for i := 0; i < len(buf); {
// Cycle through offsets which make a 137 byte sequence.
// Because 137 is prime this sequence should exercise all corner cases.
offsets := [17]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1}
for _, j := range offsets {
if v := len(buf) - i; v < j {
j = v
}
d.Write(buf[i : i+j])
i += j
}
}
got := d.Sum(nil)
if !bytes.Equal(got, want) {
t.Errorf("Unaligned writes, implementation=%s, alg=%s\ngot %q, want %q", impl, alg, got, want)
}
}
})
}
// TestAppend checks that appending works when reallocation is necessary. // TestAppend checks that appending works when reallocation is necessary.
func TestAppend(t *testing.T) { func TestAppend(t *testing.T) {
testUnalignedAndGeneric(t, func(impl string) { testUnalignedAndGeneric(t, func(impl string) {

View file

@ -24,7 +24,6 @@ import (
"runtime" "runtime"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/eth/gasprice" "github.com/ethereum/go-ethereum/eth/gasprice"
@ -115,7 +114,3 @@ type Config struct {
PowTest bool `toml:"-"` PowTest bool `toml:"-"`
PowShared bool `toml:"-"` PowShared bool `toml:"-"`
} }
type configMarshaling struct {
ExtraData hexutil.Bytes
}

View file

@ -54,7 +54,6 @@ type PublicFilterAPI struct {
backend Backend backend Backend
useMipMap bool useMipMap bool
mux *event.TypeMux mux *event.TypeMux
quit chan struct{}
chainDb ethdb.Database chainDb ethdb.Database
events *EventSystem events *EventSystem
filtersMu sync.Mutex filtersMu sync.Mutex

View file

@ -20,7 +20,6 @@ import (
"context" "context"
"math" "math"
"math/big" "math/big"
"time"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
@ -42,8 +41,6 @@ type Filter struct {
backend Backend backend Backend
useMipMap bool useMipMap bool
created time.Time
db ethdb.Database db ethdb.Database
begin, end int64 begin, end int64
addresses []common.Address addresses []common.Address

View file

@ -1,34 +0,0 @@
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package ethdb
import (
"os"
"path/filepath"
"github.com/ethereum/go-ethereum/common"
)
func newDb() *LDBDatabase {
file := filepath.Join("/", "tmp", "ldbtesttmpfile")
if common.FileExist(file) {
os.RemoveAll(file)
}
db, _ := NewLDBDatabase(file, 0, 0)
return db
}

View file

@ -39,7 +39,6 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/les" "github.com/ethereum/go-ethereum/les"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
@ -52,8 +51,6 @@ const historyUpdateRange = 50
// Service implements an Ethereum netstats reporting daemon that pushes local // Service implements an Ethereum netstats reporting daemon that pushes local
// chain statistics up to a monitoring server. // chain statistics up to a monitoring server.
type Service struct { type Service struct {
stack *node.Node // Temporary workaround, remove when API finalized
server *p2p.Server // Peer-to-peer server to retrieve networking infos server *p2p.Server // Peer-to-peer server to retrieve networking infos
eth *eth.Ethereum // Full Ethereum service if monitoring a full node eth *eth.Ethereum // Full Ethereum service if monitoring a full node
les *les.LightEthereum // Light Ethereum service if monitoring a light node les *les.LightEthereum // Light Ethereum service if monitoring a light node

View file

@ -39,10 +39,9 @@ type Feed struct {
sendCases caseList // the active set of select cases used by Send sendCases caseList // the active set of select cases used by Send
// The inbox holds newly subscribed channels until they are added to sendCases. // The inbox holds newly subscribed channels until they are added to sendCases.
mu sync.Mutex mu sync.Mutex
inbox caseList inbox caseList
etype reflect.Type etype reflect.Type
closed bool
} }
// This is the index of the first actual subscription channel in sendCases. // This is the index of the first actual subscription channel in sendCases.

View file

@ -48,7 +48,6 @@ import (
const ( const (
defaultGas = 90000 defaultGas = 90000
defaultGasPrice = 50 * params.Shannon defaultGasPrice = 50 * params.Shannon
emptyHex = "0x"
) )
// PublicEthereumAPI provides an API to access Ethereum related information. // PublicEthereumAPI provides an API to access Ethereum related information.
@ -634,10 +633,8 @@ func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr
// Wait for the context to be done and cancel the evm. Even if the // Wait for the context to be done and cancel the evm. Even if the
// EVM has finished, cancelling may be done (repeatedly) // EVM has finished, cancelling may be done (repeatedly)
go func() { go func() {
select { <-ctx.Done()
case <-ctx.Done(): evm.Cancel()
evm.Cancel()
}
}() }()
// Setup the gas pool (also for unmetered requests) // Setup the gas pool (also for unmetered requests)
@ -1393,7 +1390,7 @@ func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (strin
if block == nil { if block == nil {
return "", fmt.Errorf("block #%d not found", number) return "", fmt.Errorf("block #%d not found", number)
} }
return fmt.Sprintf("%s", block), nil return block.String(), nil
} }
// SeedHash retrieves the seed hash of a block. // SeedHash retrieves the seed hash of a block.

View file

@ -65,14 +65,6 @@ func prettyError(vm *otto.Otto, err error, w io.Writer) {
fmt.Fprint(w, ErrorColor("%s", failure)) fmt.Fprint(w, ErrorColor("%s", failure))
} }
// jsErrorString adds a backtrace to errors generated by otto.
func jsErrorString(err error) string {
if ottoErr, ok := err.(*otto.Error); ok {
return ottoErr.String()
}
return err.Error()
}
func (re *JSRE) prettyPrintJS(call otto.FunctionCall) otto.Value { func (re *JSRE) prettyPrintJS(call otto.FunctionCall) otto.Value {
for _, v := range call.ArgumentList { for _, v := range call.ArgumentList {
prettyPrint(call.Otto, v, re.output) prettyPrint(call.Otto, v, re.output)

View file

@ -69,8 +69,6 @@ func errResp(code errCode, format string, v ...interface{}) error {
return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...)) return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
} }
type hashFetcherFn func(common.Hash) error
type BlockChain interface { type BlockChain interface {
HasHeader(hash common.Hash) bool HasHeader(hash common.Hash) bool
GetHeader(hash common.Hash, number uint64) *types.Header GetHeader(hash common.Hash, number uint64) *types.Header
@ -117,10 +115,6 @@ type ProtocolManager struct {
quitSync chan struct{} quitSync chan struct{}
noMorePeers chan struct{} noMorePeers chan struct{}
syncMu sync.Mutex
syncing bool
syncDone chan struct{}
// wait group is used for graceful shutdowns during downloading // wait group is used for graceful shutdowns during downloading
// and processing // and processing
wg sync.WaitGroup wg sync.WaitGroup

View file

@ -26,8 +26,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie"
) )
func expectResponse(r p2p.MsgReader, msgcode, reqID, bv uint64, data interface{}) error { func expectResponse(r p2p.MsgReader, msgcode, reqID, bv uint64, data interface{}) error {
@ -301,38 +299,3 @@ func testGetReceipt(t *testing.T, protocol int) {
// Tests that trie merkle proofs can be retrieved // Tests that trie merkle proofs can be retrieved
func TestGetProofsLes1(t *testing.T) { testGetReceipt(t, 1) } func TestGetProofsLes1(t *testing.T) { testGetReceipt(t, 1) }
func testGetProofs(t *testing.T, protocol int) {
// Assemble the test environment
pm, db, _ := newTestProtocolManagerMust(t, false, 4, testChainGen)
bc := pm.blockchain.(*core.BlockChain)
peer, _ := newTestPeer(t, "peer", protocol, pm, true)
defer peer.close()
var proofreqs []ProofReq
var proofs [][]rlp.RawValue
accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr, {}}
for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
header := bc.GetHeaderByNumber(i)
root := header.Root
trie, _ := trie.New(root, db)
for _, acc := range accounts {
req := ProofReq{
BHash: header.Hash(),
Key: acc[:],
}
proofreqs = append(proofreqs, req)
proof := trie.Prove(crypto.Keccak256(acc[:]))
proofs = append(proofs, proof)
}
}
// Send the proof request and verify the response
cost := peer.GetRequestCost(GetProofsMsg, len(proofreqs))
sendRequest(peer.app, GetProofsMsg, 42, cost, proofreqs)
if err := expectResponse(peer.app, ProofsMsg, 42, testBufLimit, proofs); err != nil {
t.Errorf("proofs mismatch: %v", err)
}
}

View file

@ -20,7 +20,6 @@
package les package les
import ( import (
"crypto/ecdsa"
"crypto/rand" "crypto/rand"
"math/big" "math/big"
"sync" "sync"
@ -221,14 +220,6 @@ func (p *testTxPool) GetTransactions() types.Transactions {
return txs return txs
} }
// newTestTransaction create a new dummy transaction.
func newTestTransaction(from *ecdsa.PrivateKey, nonce uint64, datasize int) *types.Transaction {
tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize))
tx, _ = types.SignTx(tx, types.HomesteadSigner{}, from)
return tx
}
// testPeer is a simulated peer to allow testing direct network calls. // testPeer is a simulated peer to allow testing direct network calls.
type testPeer struct { type testPeer struct {
net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging

View file

@ -43,13 +43,13 @@ type odrPeerSelector interface {
type LesOdr struct { type LesOdr struct {
light.OdrBackend light.OdrBackend
db ethdb.Database db ethdb.Database
stop chan struct{} stop chan struct{}
removePeer peerDropFn removePeer peerDropFn
mlock, clock sync.Mutex mlock sync.Mutex
sentReqs map[uint64]*sentReq sentReqs map[uint64]*sentReq
serverPool odrPeerSelector serverPool odrPeerSelector
reqDist *requestDistributor reqDist *requestDistributor
} }
func NewLesOdr(db ethdb.Database) *LesOdr { func NewLesOdr(db ethdb.Database) *LesOdr {

View file

@ -158,7 +158,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai
func testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) { func testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
// Assemble the test environment // Assemble the test environment
pm, db, odr := newTestProtocolManagerMust(t, false, 4, testChainGen) pm, db, _ := newTestProtocolManagerMust(t, false, 4, testChainGen)
lpm, ldb, odr := newTestProtocolManagerMust(t, true, 0, nil) lpm, ldb, odr := newTestProtocolManagerMust(t, true, 0, nil)
_, err1, lpeer, err2 := newTestPeerPair("peer", protocol, pm, lpm) _, err1, lpeer, err2 := newTestPeerPair("peer", protocol, pm, lpm)
pool := &testServerPool{} pool := &testServerPool{}

View file

@ -38,10 +38,7 @@ var (
errNotRegistered = errors.New("peer is not registered") errNotRegistered = errors.New("peer is not registered")
) )
const ( const maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam)
maxHeadInfoLen = 20
maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam)
)
type peer struct { type peer struct {
*p2p.Peer *p2p.Peer

View file

@ -23,7 +23,6 @@ import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
@ -105,12 +104,6 @@ var errorToString = map[int]string{
ErrHandshakeMissingKey: "Key missing from handshake message", ErrHandshakeMissingKey: "Key missing from handshake message",
} }
type chainManager interface {
GetBlockHashesFromHash(hash common.Hash, amount uint64) (hashes []common.Hash)
GetBlock(hash common.Hash) (block *types.Block)
Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash)
}
// announceData is the network packet for the block announcements. // announceData is the network packet for the block announcements.
type announceData struct { type announceData struct {
Hash common.Hash // Hash of one particular block being announced Hash common.Hash // Hash of one particular block being announced
@ -118,11 +111,6 @@ type announceData struct {
Td *big.Int // Total difficulty of one particular block being announced Td *big.Int // Total difficulty of one particular block being announced
ReorgDepth uint64 ReorgDepth uint64
Update keyValueList Update keyValueList
haveHeaders uint64 // we have the headers of the remote peer's chain up to this number
headKnown bool
requested bool
next *announceData
} }
type blockInfo struct { type blockInfo struct {
@ -131,12 +119,6 @@ type blockInfo struct {
Td *big.Int // Total difficulty of one particular block being announced Td *big.Int // Total difficulty of one particular block being announced
} }
// getBlockHashesData is the network packet for the hash based hash retrieval.
type getBlockHashesData struct {
Hash common.Hash
Amount uint64
}
// getBlockHeadersData represents a block header query. // getBlockHeadersData represents a block header query.
type getBlockHeadersData struct { type getBlockHeadersData struct {
Origin hashOrNumber // Block from which to retrieve headers Origin hashOrNumber // Block from which to retrieve headers
@ -181,15 +163,6 @@ func (hn *hashOrNumber) DecodeRLP(s *rlp.Stream) error {
return err return err
} }
// newBlockData is the network packet for the block propagation message.
type newBlockData struct {
Block *types.Block
TD *big.Int
}
// blockBodiesData is the network packet for block content distribution.
type blockBodiesData []*types.Body
// CodeData is the network response packet for a node data retrieval. // CodeData is the network response packet for a node data retrieval.
type CodeData []struct { type CodeData []struct {
Value []byte Value []byte

View file

@ -41,7 +41,6 @@ type LesServer struct {
fcManager *flowcontrol.ClientManager // nil if our node is client only fcManager *flowcontrol.ClientManager // nil if our node is client only
fcCostStats *requestCostStats fcCostStats *requestCostStats
defParams *flowcontrol.ServerParams defParams *flowcontrol.ServerParams
stopped bool
} }
func NewLesServer(eth *eth.Ethereum, config *eth.Config) (*LesServer, error) { func NewLesServer(eth *eth.Ethereum, config *eth.Config) (*LesServer, error) {
@ -103,16 +102,6 @@ func (list RequestCostList) decode() requestCostTable {
return table return table
} }
func (table requestCostTable) encode() RequestCostList {
list := make(RequestCostList, len(table))
for idx, code := range reqList {
list[idx].MsgCode = code
list[idx].BaseCost = table[code].baseCost
list[idx].ReqCost = table[code].reqCost
}
return list
}
type linReg struct { type linReg struct {
sumX, sumY, sumXX, sumXY float64 sumX, sumY, sumXX, sumXY float64
cnt uint64 cnt uint64

View file

@ -73,7 +73,6 @@ const (
// and a short term value which is adjusted exponentially with a factor of // and a short term value which is adjusted exponentially with a factor of
// pstatRecentAdjust with each dial/connection and also returned exponentially // pstatRecentAdjust with each dial/connection and also returned exponentially
// to the average with the time constant pstatReturnToMeanTC // to the average with the time constant pstatReturnToMeanTC
pstatRecentAdjust = 0.1
pstatReturnToMeanTC = time.Hour pstatReturnToMeanTC = time.Hour
// node address selection weight is dropped by a factor of exp(-addrFailDropLn) after // node address selection weight is dropped by a factor of exp(-addrFailDropLn) after
// each unsuccessful connection (restored after a successful one) // each unsuccessful connection (restored after a successful one)
@ -83,9 +82,6 @@ const (
responseScoreTC = time.Millisecond * 100 responseScoreTC = time.Millisecond * 100
delayScoreTC = time.Second * 5 delayScoreTC = time.Second * 5
timeoutPow = 10 timeoutPow = 10
// peerSelectMinWeight is added to calculated weights at request peer selection
// to give poorly performing peers a little chance of coming back
peerSelectMinWeight = 0.005
// initStatsWeight is used to initialize previously unknown peers with good // initStatsWeight is used to initialize previously unknown peers with good
// statistics to give a chance to prove themselves // statistics to give a chance to prove themselves
initStatsWeight = 1 initStatsWeight = 1

View file

@ -25,11 +25,6 @@ import (
"github.com/ethereum/go-ethereum/light" "github.com/ethereum/go-ethereum/light"
) )
const (
//forceSyncCycle = 10 * time.Second // Time interval to force syncs, even if few peers are available
minDesiredPeerCount = 5 // Amount of peers desired to start syncing
)
// syncer is responsible for periodically synchronising with the network, both // syncer is responsible for periodically synchronising with the network, both
// downloading hashes and blocks as well as handling the announcement handler. // downloading hashes and blocks as well as handling the announcement handler.
func (pm *ProtocolManager) syncer() { func (pm *ProtocolManager) syncer() {

View file

@ -52,7 +52,6 @@ type LightChain struct {
mu sync.RWMutex mu sync.RWMutex
chainmu sync.RWMutex chainmu sync.RWMutex
procmu sync.RWMutex
bodyCache *lru.Cache // Cache for the most recent block bodies bodyCache *lru.Cache // Cache for the most recent block bodies
bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format

View file

@ -18,7 +18,6 @@ package light
import ( import (
"context" "context"
"fmt"
"math/big" "math/big"
"testing" "testing"
@ -117,13 +116,6 @@ func testFork(t *testing.T, LightChain *LightChain, i, n int, comparator func(td
comparator(tdPre, tdPost) comparator(tdPre, tdPost)
} }
func printChain(bc *LightChain) {
for i := bc.CurrentHeader().Number.Uint64(); i > 0; i-- {
b := bc.GetHeaderByNumber(uint64(i))
fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty)
}
}
// testHeaderChainImport tries to process a chain of header, writing them into // testHeaderChainImport tries to process a chain of header, writing them into
// the database if successful. // the database if successful.
func testHeaderChainImport(chain []*types.Header, lightchain *LightChain) error { func testHeaderChainImport(chain []*types.Header, lightchain *LightChain) error {

View file

@ -330,7 +330,7 @@ func escapeString(s string) string {
needsEscape = true needsEscape = true
} }
} }
if needsEscape == false && needsQuotes == false { if !needsEscape && !needsQuotes {
return s return s
} }
e := stringBufPool.Get().(*bytes.Buffer) e := stringBufPool.Get().(*bytes.Buffer)

View file

@ -39,10 +39,7 @@ import (
"gopkg.in/fatih/set.v0" "gopkg.in/fatih/set.v0"
) )
const ( const resultQueueSize = 10
resultQueueSize = 10
miningLogAtDepth = 5
)
// Agent can register themself with the worker // Agent can register themself with the worker
type Agent interface { type Agent interface {
@ -109,8 +106,7 @@ type worker struct {
uncleMu sync.Mutex uncleMu sync.Mutex
possibleUncles map[common.Hash]*types.Block possibleUncles map[common.Hash]*types.Block
txQueueMu sync.Mutex txQueue map[common.Hash]*types.Transaction
txQueue map[common.Hash]*types.Transaction
unconfirmed *unconfirmedBlocks // set of locally mined blocks pending canonicalness confirmations unconfirmed *unconfirmedBlocks // set of locally mined blocks pending canonicalness confirmations

View file

@ -40,7 +40,6 @@ var (
datadirDefaultKeyStore = "keystore" // Path within the datadir to the keystore datadirDefaultKeyStore = "keystore" // Path within the datadir to the keystore
datadirStaticNodes = "static-nodes.json" // Path within the datadir to the static node list datadirStaticNodes = "static-nodes.json" // Path within the datadir to the static node list
datadirTrustedNodes = "trusted-nodes.json" // Path within the datadir to the trusted node list datadirTrustedNodes = "trusted-nodes.json" // Path within the datadir to the trusted node list
datadirNodeDatabase = "nodes" // Path within the datadir to store the node infos
) )
// Config represents a small collection of configuration values to fine tune the // Config represents a small collection of configuration values to fine tune the

View file

@ -41,12 +41,10 @@ func NewNoopService(*ServiceContext) (Service, error) { return new(NoopService),
type NoopServiceA struct{ NoopService } type NoopServiceA struct{ NoopService }
type NoopServiceB struct{ NoopService } type NoopServiceB struct{ NoopService }
type NoopServiceC struct{ NoopService } type NoopServiceC struct{ NoopService }
type NoopServiceD struct{ NoopService }
func NewNoopServiceA(*ServiceContext) (Service, error) { return new(NoopServiceA), nil } func NewNoopServiceA(*ServiceContext) (Service, error) { return new(NoopServiceA), nil }
func NewNoopServiceB(*ServiceContext) (Service, error) { return new(NoopServiceB), nil } func NewNoopServiceB(*ServiceContext) (Service, error) { return new(NoopServiceB), nil }
func NewNoopServiceC(*ServiceContext) (Service, error) { return new(NoopServiceC), nil } func NewNoopServiceC(*ServiceContext) (Service, error) { return new(NoopServiceC), nil }
func NewNoopServiceD(*ServiceContext) (Service, error) { return new(NoopServiceD), nil }
// InstrumentedService is an implementation of Service for which all interface // InstrumentedService is an implementation of Service for which all interface
// methods can be instrumented both return value as well as event hook wise. // methods can be instrumented both return value as well as event hook wise.

View file

@ -49,7 +49,6 @@ var (
// Timeouts // Timeouts
const ( const (
respTimeout = 500 * time.Millisecond respTimeout = 500 * time.Millisecond
sendTimeout = 500 * time.Millisecond
expiration = 20 * time.Second expiration = 20 * time.Second
ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
@ -168,7 +167,6 @@ type udp struct {
gotreply chan reply gotreply chan reply
closing chan struct{} closing chan struct{}
nat nat.Interface
*Table *Table
} }

View file

@ -37,7 +37,6 @@ import (
var ( var (
errInvalidEvent = errors.New("invalid in current state") errInvalidEvent = errors.New("invalid in current state")
errNoQuery = errors.New("no pending query") errNoQuery = errors.New("no pending query")
errWrongAddress = errors.New("unknown sender address")
) )
const ( const (
@ -86,14 +85,6 @@ type Network struct {
nursery []*Node nursery []*Node
nodes map[NodeID]*Node // tracks active nodes with state != known nodes map[NodeID]*Node // tracks active nodes with state != known
timeoutTimers map[timeoutEvent]*time.Timer timeoutTimers map[timeoutEvent]*time.Timer
// Revalidation queues.
// Nodes put on these queues will be pinged eventually.
slowRevalidateQueue []*Node
fastRevalidateQueue []*Node
// Buffers for state transition.
sendBuf []*ingressPacket
} }
// transport is implemented by the UDP transport. // transport is implemented by the UDP transport.
@ -113,10 +104,9 @@ type transport interface {
} }
type findnodeQuery struct { type findnodeQuery struct {
remote *Node remote *Node
target common.Hash target common.Hash
reply chan<- []*Node reply chan<- []*Node
nresults int // counter for received nodes
} }
type topicRegisterReq struct { type topicRegisterReq struct {
@ -658,11 +648,13 @@ loop:
if net.conn != nil { if net.conn != nil {
net.conn.Close() net.conn.Close()
} }
if refreshDone != nil { // TODO : issue #
// TODO: wait for pending refresh. //if refreshDone != nil {
//<-refreshResults // TODO: wait for pending refresh.
} //<-refreshResults
//}
// Cancel all pending timeouts. // Cancel all pending timeouts.
for _, timer := range net.timeoutTimers { for _, timer := range net.timeoutTimers {
timer.Stop() timer.Stop()
} }
@ -684,7 +676,7 @@ func (net *Network) refresh(done chan<- struct{}) {
seeds = net.nursery seeds = net.nursery
} }
if len(seeds) == 0 { if len(seeds) == 0 {
log.Trace(fmt.Sprint("no seed nodes found")) log.Trace("no seed nodes found")
close(done) close(done)
return return
} }

View file

@ -38,7 +38,6 @@ const (
hashBits = len(common.Hash{}) * 8 hashBits = len(common.Hash{}) * 8
nBuckets = hashBits + 1 // Number of buckets nBuckets = hashBits + 1 // Number of buckets
maxBondingPingPongs = 16
maxFindnodeFailures = 5 maxFindnodeFailures = 5
) )

View file

@ -18,9 +18,9 @@ package discv5
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"errors"
"fmt" "fmt"
"math/rand" "math/rand"
"net" "net"
"reflect" "reflect"
"testing" "testing"
@ -31,6 +31,8 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
) )
var errTimeout = errors.New("RPC timeout")
type nullTransport struct{} type nullTransport struct{}
func (nullTransport) sendPing(remote *Node, remoteAddr *net.UDPAddr) []byte { return []byte{1} } func (nullTransport) sendPing(remote *Node, remoteAddr *net.UDPAddr) []byte { return []byte{1} }
@ -139,17 +141,6 @@ func TestBucket_bumpNoDuplicates(t *testing.T) {
} }
} }
// fillBucket inserts nodes into the given bucket until
// it is full. The node's IDs dont correspond to their
// hashes.
func fillBucket(tab *Table, ld int) (last *Node) {
b := tab.buckets[ld]
for len(b.entries) < bucketSize {
b.entries = append(b.entries, nodeAtDistance(tab.self.sha, ld))
}
return b.entries[bucketSize-1]
}
// nodeAtDistance creates a node for which logdist(base, n.sha) == ld. // nodeAtDistance creates a node for which logdist(base, n.sha) == ld.
// The node's ID does not correspond to n.sha. // The node's ID does not correspond to n.sha.
func nodeAtDistance(base common.Hash, ld int) (n *Node) { func nodeAtDistance(base common.Hash, ld int) (n *Node) {
@ -161,10 +152,6 @@ func nodeAtDistance(base common.Hash, ld int) (n *Node) {
type pingRecorder struct{ responding, pinged map[NodeID]bool } type pingRecorder struct{ responding, pinged map[NodeID]bool }
func newPingRecorder() *pingRecorder {
return &pingRecorder{make(map[NodeID]bool), make(map[NodeID]bool)}
}
func (t *pingRecorder) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { func (t *pingRecorder) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) {
panic("findnode called on pingRecorder") panic("findnode called on pingRecorder")
} }

View file

@ -36,25 +36,15 @@ const Version = 4
// Errors // Errors
var ( var (
errPacketTooSmall = errors.New("too small") errPacketTooSmall = errors.New("too small")
errBadHash = errors.New("bad hash") errBadHash = errors.New("bad hash")
errExpired = errors.New("expired")
errUnsolicitedReply = errors.New("unsolicited reply")
errUnknownNode = errors.New("unknown node")
errTimeout = errors.New("RPC timeout")
errClockWarp = errors.New("reply deadline too far in the future")
errClosed = errors.New("socket closed")
) )
// Timeouts // Timeouts
const ( const (
respTimeout = 500 * time.Millisecond respTimeout = 500 * time.Millisecond
sendTimeout = 500 * time.Millisecond expiration = 20 * time.Second
expiration = 20 * time.Second driftThreshold = 10 * time.Second // Allowed clock drift before warning user
ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
driftThreshold = 10 * time.Second // Allowed clock drift before warning user
) )
// RPC request structures // RPC request structures
@ -194,10 +184,6 @@ func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint {
return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort} return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort}
} }
func (e1 rpcEndpoint) equal(e2 rpcEndpoint) bool {
return e1.UDP == e2.UDP && e1.TCP == e2.TCP && e1.IP.Equal(e2.IP)
}
func nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*Node, error) { func nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*Node, error) {
if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil { if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
return nil, err return nil, err
@ -232,7 +218,6 @@ type udp struct {
conn conn conn conn
priv *ecdsa.PrivateKey priv *ecdsa.PrivateKey
ourEndpoint rpcEndpoint ourEndpoint rpcEndpoint
nat nat.Interface
net *Network net *Network
} }

View file

@ -390,6 +390,20 @@ func TestForwardCompatibility(t *testing.T) {
} }
} }
// WriteToUDP queues a datagram.
func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) {
msg := make([]byte, len(b))
copy(msg, b)
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return 0, errors.New("closed")
}
c.queue = append(c.queue, msg)
c.cond.Signal()
return len(b), nil
}
// dgramPipe is a fake UDP socket. It queues all sent datagrams. // dgramPipe is a fake UDP socket. It queues all sent datagrams.
type dgramPipe struct { type dgramPipe struct {
mu *sync.Mutex mu *sync.Mutex
@ -408,20 +422,6 @@ func newpipe() *dgramPipe {
} }
} }
// WriteToUDP queues a datagram.
func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) {
msg := make([]byte, len(b))
copy(msg, b)
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return 0, errors.New("closed")
}
c.queue = append(c.queue, msg)
c.cond.Signal()
return len(b), nil
}
// ReadFromUDP just hangs until the pipe is closed. // ReadFromUDP just hangs until the pipe is closed.
func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
<-c.closing <-c.closing

View file

@ -44,8 +44,6 @@ const (
discMsg = 0x01 discMsg = 0x01
pingMsg = 0x02 pingMsg = 0x02
pongMsg = 0x03 pongMsg = 0x03
getPeersMsg = 0x04
peersMsg = 0x05
) )
// protoHandshake is the RLP structure of the protocol handshake. // protoHandshake is the RLP structure of the protocol handshake.

View file

@ -35,9 +35,7 @@ import (
) )
const ( const (
defaultDialTimeout = 15 * time.Second defaultDialTimeout = 15 * time.Second
refreshPeersInterval = 30 * time.Second
staticPeerCheckInterval = 15 * time.Second
// Maximum number of concurrently handshaking inbound connections. // Maximum number of concurrently handshaking inbound connections.
maxAcceptConns = 50 maxAcceptConns = 50

View file

@ -29,11 +29,7 @@ import (
"gopkg.in/fatih/set.v0" "gopkg.in/fatih/set.v0"
) )
const ( const MetadataApi = "rpc"
notificationBufferSize = 10000 // max buffered notifications before codec is closed
MetadataApi = "rpc"
)
// CodecOption specifies which type of messages this codec supports // CodecOption specifies which type of messages this codec supports
type CodecOption int type CodecOption int
@ -124,16 +120,6 @@ func (s *Server) RegisterName(name string, rcvr interface{}) error {
return nil return nil
} }
// hasOption returns true if option is included in options, otherwise false
func hasOption(option CodecOption, options []CodecOption) bool {
for _, o := range options {
if option == o {
return true
}
}
return false
}
// serveRequest will reads requests from the codec, calls the RPC callback and // serveRequest will reads requests from the codec, calls the RPC callback and
// writes the response to the given codec. // writes the response to the given codec.
// //
@ -148,13 +134,11 @@ func (s *Server) serveRequest(codec ServerCodec, singleShot bool, options CodecO
const size = 64 << 10 const size = 64 << 10
buf := make([]byte, size) buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)] buf = buf[:runtime.Stack(buf, false)]
log.Error(fmt.Sprint(string(buf))) log.Error(string(buf))
} }
s.codecsMu.Lock() s.codecsMu.Lock()
s.codecs.Remove(codec) s.codecs.Remove(codec)
s.codecsMu.Unlock() s.codecsMu.Unlock()
return
}() }()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
@ -246,7 +230,7 @@ func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption) {
// close all codecs which will cancel pending requests/subscriptions. // close all codecs which will cancel pending requests/subscriptions.
func (s *Server) Stop() { func (s *Server) Stop() {
if atomic.CompareAndSwapInt32(&s.run, 1, 0) { if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
log.Debug(fmt.Sprint("RPC Server shutdown initiatied")) log.Debug("RPC Server shutdown initiatied")
s.codecsMu.Lock() s.codecsMu.Lock()
defer s.codecsMu.Unlock() defer s.codecsMu.Unlock()
s.codecs.Each(func(c interface{}) bool { s.codecs.Each(func(c interface{}) bool {

View file

@ -53,7 +53,6 @@ type notifierKey struct{}
type Notifier struct { type Notifier struct {
codec ServerCodec codec ServerCodec
subMu sync.RWMutex // guards active and inactive maps subMu sync.RWMutex // guards active and inactive maps
stopped bool
active map[ID]*Subscription active map[ID]*Subscription
inactive map[ID]*Subscription inactive map[ID]*Subscription
} }

View file

@ -48,7 +48,6 @@ type callback struct {
// service represents a registered object // service represents a registered object
type service struct { type service struct {
name string // name for service name string // name for service
rcvr reflect.Value // receiver of methods for the service
typ reflect.Type // receiver type typ reflect.Type // receiver type
callbacks callbacks // registered handlers callbacks callbacks // registered handlers
subscriptions subscriptions // available subscriptions/notifications subscriptions subscriptions // available subscriptions/notifications
@ -58,7 +57,6 @@ type service struct {
type serverRequest struct { type serverRequest struct {
id interface{} id interface{}
svcname string svcname string
rcvr reflect.Value
callb *callback callb *callback
args []reflect.Value args []reflect.Value
isUnsubscribe bool isUnsubscribe bool
@ -72,9 +70,8 @@ type subscriptionRegistry map[string]*callback // collection of subscription cal
// Server represents a RPC server // Server represents a RPC server
type Server struct { type Server struct {
services serviceRegistry services serviceRegistry
muSubcriptions sync.Mutex // protects subscriptions subscriptions subscriptionRegistry
subscriptions subscriptionRegistry
run int32 run int32
codecsMu sync.Mutex codecsMu sync.Mutex

View file

@ -119,21 +119,6 @@ func isHexNum(t reflect.Type) bool {
return t == bigIntType return t == bigIntType
} }
var blockNumberType = reflect.TypeOf((*BlockNumber)(nil)).Elem()
// Indication if the given block is a BlockNumber
func isBlockNumber(t reflect.Type) bool {
if t == nil {
return false
}
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t == blockNumberType
}
// suitableCallbacks iterates over the methods of the given type. It will determine if a method satisfies the criteria // suitableCallbacks iterates over the methods of the given type. It will determine if a method satisfies the criteria
// for a RPC callback or a subscription callback and adds it to the collection of callbacks or subscriptions. See server // for a RPC callback or a subscription callback and adds it to the collection of callbacks or subscriptions. See server
// documentation for a summary of these criteria. // documentation for a summary of these criteria.

View file

@ -34,11 +34,7 @@ import (
"github.com/ethereum/go-ethereum/swarm/storage" "github.com/ethereum/go-ethereum/swarm/storage"
) )
var ( var hashMatcher = regexp.MustCompile("^[0-9A-Fa-f]{64}")
hashMatcher = regexp.MustCompile("^[0-9A-Fa-f]{64}")
slashes = regexp.MustCompile("/+")
domainAndVersion = regexp.MustCompile("[@:;,]+")
)
type Resolver interface { type Resolver interface {
Resolve(string) (common.Hash, error) Resolve(string) (common.Hash, error)
@ -356,5 +352,5 @@ func (self *Api) BuildDirectoryTree(mhash string, nameresolver bool) (key storag
manifestEntryMap[suffix] = entry manifestEntryMap[suffix] = entry
}) })
return key, manifestEntryMap, nil return key, manifestEntryMap, err
} }

View file

@ -89,9 +89,6 @@ func TestClientUploadDownloadFiles(t *testing.T) {
if file.Size != int64(len(expected)) { if file.Size != int64(len(expected)) {
t.Fatalf("expected downloaded file to be %d bytes, got %d", len(expected), file.Size) t.Fatalf("expected downloaded file to be %d bytes, got %d", len(expected), file.Size)
} }
if file.ContentType != file.ContentType {
t.Fatalf("expected downloaded file to have type %q, got %q", file.ContentType, file.ContentType)
}
data, err := ioutil.ReadAll(file) data, err := ioutil.ReadAll(file)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -235,9 +232,7 @@ func TestClientFileList(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
paths := make([]string, 0, len(list.CommonPrefixes)+len(list.Entries)) paths := make([]string, 0, len(list.CommonPrefixes)+len(list.Entries))
for _, prefix := range list.CommonPrefixes { paths = append(paths, list.CommonPrefixes...)
paths = append(paths, prefix)
}
for _, entry := range list.Entries { for _, entry := range list.Entries {
paths = append(paths, entry.Path) paths = append(paths, entry.Path)
} }

View file

@ -224,7 +224,7 @@ func (s *Server) handleMultipartUpload(req *Request, boundary string, mw *api.Ma
if err != nil { if err != nil {
return fmt.Errorf("error copying multipart content: %s", err) return fmt.Errorf("error copying multipart content: %s", err)
} }
if _, err := tmp.Seek(0, os.SEEK_SET); err != nil { if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("error copying multipart content: %s", err) return fmt.Errorf("error copying multipart content: %s", err)
} }
reader = tmp reader = tmp

View file

@ -93,7 +93,7 @@ func TestBzzrGetPath(t *testing.T) {
isexpectedfailrequest = true isexpectedfailrequest = true
} }
} }
if isexpectedfailrequest == false { if !isexpectedfailrequest {
t.Fatalf("Response body does not match, expected: %v, got %v", testmanifest[v], string(respbody)) t.Fatalf("Response body does not match, expected: %v, got %v", testmanifest[v], string(respbody))
} }
} }
@ -116,12 +116,16 @@ func TestBzzrGetPath(t *testing.T) {
var respbody []byte var respbody []byte
resp, err = http.Get(url) resp, err = http.Get(url)
if err != nil { if err != nil {
t.Fatalf("Request failed: %v", err) t.Fatalf("Request failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
respbody, err = ioutil.ReadAll(resp.Body) respbody, err = ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Reading body failed: %v", err)
}
if string(respbody) != nonhashresponses[i] { if string(respbody) != nonhashresponses[i] {
t.Fatalf("Non-Hash response body does not match, expected: %v, got: %v", nonhashresponses[i], string(respbody)) t.Fatalf("Non-Hash response body does not match, expected: %v, got: %v", nonhashresponses[i], string(respbody))
} }

View file

@ -115,7 +115,7 @@ func mountDir(t *testing.T, api *api.Api, files map[string]fileInfo, bzzHash str
} }
// Test listMounts // Test listMounts
if found == false { if !found {
t.Fatalf("Error getting mounts information for %v: %v", mountDir, err) t.Fatalf("Error getting mounts information for %v: %v", mountDir, err)
} }
@ -164,7 +164,7 @@ func compareGeneratedFileWithFileInMount(t *testing.T, files map[string]fileInfo
t.Fatalf("Could not readfile %v : %v", fname, err) t.Fatalf("Could not readfile %v : %v", fname, err)
} }
if bytes.Compare(fileContents, finfo.contents) != 0 { if !bytes.Equal(fileContents, finfo.contents) {
t.Fatalf("File %v contents mismatch: %v , %v", fname, fileContents, finfo.contents) t.Fatalf("File %v contents mismatch: %v , %v", fname, fileContents, finfo.contents)
} }
@ -212,10 +212,7 @@ func IsDirEmpty(name string) bool {
defer f.Close() defer f.Close()
_, err = f.Readdirnames(1) _, err = f.Readdirnames(1)
if err == io.EOF { return err == io.EOF
return true
}
return false
} }
func testMountListAndUnmount(api *api.Api, t *testing.T) { func testMountListAndUnmount(api *api.Api, t *testing.T) {
@ -381,11 +378,15 @@ func testUnmountWhenResourceBusy(api *api.Api, t *testing.T) {
actualPath := filepath.Join(testMountDir, "2.txt") actualPath := filepath.Join(testMountDir, "2.txt")
d, err := os.OpenFile(actualPath, os.O_RDWR, os.FileMode(0700)) d, err := os.OpenFile(actualPath, os.O_RDWR, os.FileMode(0700))
// catching this error fails the test
//if err != nil {
// t.Fatalf("could not open file %v", bzzHash)
//}
d.Write(getRandomBtes(10)) d.Write(getRandomBtes(10))
_, err = swarmfs.Unmount(testMountDir) _, err = swarmfs.Unmount(testMountDir)
if err != nil { if err != nil {
t.Fatalf("could not unmount %v", bzzHash) t.Fatalf("could not unmount %v", bzzHash)
} }
d.Close() d.Close()
@ -419,7 +420,7 @@ func testSeekInMultiChunkFile(api *api.Api, t *testing.T) {
d.Read(contents) d.Read(contents)
finfo := files["1.txt"] finfo := files["1.txt"]
if bytes.Compare(finfo.contents[:6024][5000:], contents) != 0 { if !bytes.Equal(finfo.contents[:6024][5000:], contents) {
t.Fatalf("File seek contents mismatch") t.Fatalf("File seek contents mismatch")
} }
d.Close() d.Close()

View file

@ -58,14 +58,6 @@ type MountInfo struct {
lock *sync.RWMutex lock *sync.RWMutex
} }
// Inode numbers need to be unique, they are used for caching inside fuse
func newInode() uint64 {
inodeLock.Lock()
defer inodeLock.Unlock()
inode += 1
return inode
}
func NewMountInfo(mhash, mpoint string, sapi *api.Api) *MountInfo { func NewMountInfo(mhash, mpoint string, sapi *api.Api) *MountInfo {
newMountInfo := &MountInfo{ newMountInfo := &MountInfo{
MountPoint: mpoint, MountPoint: mpoint,
@ -102,7 +94,7 @@ func (self *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) {
} }
log.Info(fmt.Sprintf("Attempting to mount %s ", cleanedMountPoint)) log.Info(fmt.Sprintf("Attempting to mount %s ", cleanedMountPoint))
key, manifestEntryMap, err := self.swarmApi.BuildDirectoryTree(mhash, true) _, manifestEntryMap, err := self.swarmApi.BuildDirectoryTree(mhash, true)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -116,7 +108,7 @@ func (self *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) {
for suffix, entry := range manifestEntryMap { for suffix, entry := range manifestEntryMap {
key = common.Hex2Bytes(entry.Hash) key := common.Hex2Bytes(entry.Hash)
fullpath := "/" + suffix fullpath := "/" + suffix
basepath := filepath.Dir(fullpath) basepath := filepath.Dir(fullpath)

View file

@ -420,8 +420,8 @@ func (self *Kademlia) String() string {
} }
} }
rows = append(rows, strings.Join(row, " ")) rows = append(rows, strings.Join(row, " "))
if i == self.MaxProx { //if i == self.MaxProx {
} //}
} }
rows = append(rows, "=========================================================================") rows = append(rows, "=========================================================================")
return strings.Join(rows, "\n") return strings.Join(rows, "\n")

View file

@ -156,14 +156,13 @@ func (self *TreeChunker) Split(data io.Reader, size int64, chunkC chan *Chunk, s
close(errC) close(errC)
}() }()
select { err := <-errC
case err := <-errC: if err != nil {
if err != nil { close(quitC)
close(quitC) return nil, err
return nil, err
}
//TODO: add a timeout
} }
//TODO: add a timeout
return key, nil return key, nil
} }

View file

@ -209,20 +209,6 @@ func TestRandomBrokenData(t *testing.T) {
} }
} }
func readAll(reader LazySectionReader, result []byte) {
size := int64(len(result))
var end int64
for pos := int64(0); pos < size; pos += 1000 {
if pos+1000 > size {
end = size
} else {
end = pos + 1000
}
reader.ReadAt(result[pos:end], pos)
}
}
func benchReadAll(reader LazySectionReader) { func benchReadAll(reader LazySectionReader) {
size, _ := reader.Size(nil) size, _ := reader.Size(nil)
output := make([]byte, 1000) output := make([]byte, 1000)

View file

@ -43,7 +43,6 @@ const (
// key prefixes for leveldb storage // key prefixes for leveldb storage
kpIndex = 0 kpIndex = 0
kpData = 1
) )
var ( var (
@ -432,8 +431,7 @@ func (s *DbStore) setCapacity(c uint64) {
s.capacity = c s.capacity = c
if s.entryCnt > c { if s.entryCnt > c {
var ratio float32 ratio := float32(1.01) - float32(c)/float32(s.entryCnt)
ratio = float32(1.01) - float32(c)/float32(s.entryCnt)
if ratio < gcArrayFreeRatio { if ratio < gcArrayFreeRatio {
ratio = gcArrayFreeRatio ratio = gcArrayFreeRatio
} }

View file

@ -59,7 +59,6 @@ type DPA struct {
lock sync.Mutex lock sync.Mutex
running bool running bool
wg *sync.WaitGroup
quitC chan bool quitC chan bool
} }
@ -240,5 +239,4 @@ func (self *dpaChunkStore) Put(entry *Chunk) {
// Close chunk store // Close chunk store
func (self *dpaChunkStore) Close() { func (self *dpaChunkStore) Close() {
return
} }

View file

@ -75,5 +75,4 @@ func (self *LocalStore) Get(key Key) (chunk *Chunk, err error) {
// Close local store // Close local store
func (self *LocalStore) Close() { func (self *LocalStore) Close() {
return
} }

View file

@ -206,8 +206,6 @@ func (s *MemStore) Put(entry *Chunk) {
node.lastDBaccess = s.dbAccessCnt node.lastDBaccess = s.dbAccessCnt
node.updateAccess(s.accessCnt) node.updateAccess(s.accessCnt)
s.entryCnt++ s.entryCnt++
return
} }
func (s *MemStore) Get(hash Key) (chunk *Chunk, err error) { func (s *MemStore) Get(hash Key) (chunk *Chunk, err error) {
@ -324,5 +322,4 @@ func (s *MemStore) removeOldest() {
// Close memstore // Close memstore
func (s *MemStore) Close() { func (s *MemStore) Close() {
return
} }

View file

@ -19,7 +19,6 @@ package storage
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"sync"
"time" "time"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
@ -40,7 +39,6 @@ type NetStore struct {
hashfunc Hasher hashfunc Hasher
localStore *LocalStore localStore *LocalStore
cloud CloudStore cloud CloudStore
lock sync.Mutex
} }
// backend engine for cloud store // backend engine for cloud store
@ -79,11 +77,6 @@ func NewNetStore(hash Hasher, lstore *LocalStore, cloud CloudStore, params *Stor
} }
} }
const (
// maximum number of peers that a retrieved message is delivered to
requesterCount = 3
)
var ( var (
// timeout interval before retrieval is timed out // timeout interval before retrieval is timed out
searchTimeout = 3 * time.Second searchTimeout = 3 * time.Second
@ -135,5 +128,4 @@ func (self *NetStore) Get(key Key) (*Chunk, error) {
// Close netstore // Close netstore
func (self *NetStore) Close() { func (self *NetStore) Close() {
return
} }

View file

@ -50,7 +50,6 @@ type Swarm struct {
storage storage.ChunkStore // internal access to storage, common interface to cloud storage backends storage storage.ChunkStore // internal access to storage, common interface to cloud storage backends
dpa *storage.DPA // distributed preimage archive, the local API to the storage with document level storage/retrieval support dpa *storage.DPA // distributed preimage archive, the local API to the storage with document level storage/retrieval support
depo network.StorageHandler // remote request handler, interface between bzz protocol and the storage depo network.StorageHandler // remote request handler, interface between bzz protocol and the storage
cloud storage.CloudStore // procurement, cloud storage backend (can multi-cloud)
hive *network.Hive // the logistic manager hive *network.Hive // the logistic manager
backend chequebook.Backend // simple blockchain Backend backend chequebook.Backend // simple blockchain Backend
privateKey *ecdsa.PrivateKey privateKey *ecdsa.PrivateKey

View file

@ -22,7 +22,6 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http"
"os" "os"
"path/filepath" "path/filepath"
) )
@ -80,16 +79,6 @@ func readJson(reader io.Reader, value interface{}) error {
return nil return nil
} }
func readJsonHttp(uri string, value interface{}) error {
resp, err := http.Get(uri)
if err != nil {
return err
}
defer resp.Body.Close()
return readJson(resp.Body, value)
}
func readJsonFile(fn string, value interface{}) error { func readJsonFile(fn string, value interface{}) error {
file, err := os.Open(fn) file, err := os.Open(fn)
if err != nil { if err != nil {

View file

@ -104,7 +104,7 @@ func (s *WMailServer) Archive(env *whisper.Envelope) {
func (s *WMailServer) DeliverMail(peer *whisper.Peer, request *whisper.Envelope) { func (s *WMailServer) DeliverMail(peer *whisper.Peer, request *whisper.Envelope) {
if peer == nil { if peer == nil {
log.Error(fmt.Sprint("Whisper peer is nil")) log.Error("Whisper peer is nil")
return return
} }

View file

@ -166,7 +166,7 @@ func singleRequest(t *testing.T, server *WMailServer, env *whisper.Envelope, p *
} }
src[0]++ src[0]++
ok, lower, upper, topic = server.validateRequest(src, request) ok, _, _, topic = server.validateRequest(src, request)
if ok { if ok {
t.Fatalf("request validation false positive, seed: %d.", seed) t.Fatalf("request validation false positive, seed: %d.", seed)
} }

View file

@ -173,7 +173,7 @@ func (self *Whisper) Send(envelope *Envelope) error {
// Start implements node.Service, starting the background data propagation thread // Start implements node.Service, starting the background data propagation thread
// of the Whisper protocol. // of the Whisper protocol.
func (self *Whisper) Start(*p2p.Server) error { func (self *Whisper) Start(*p2p.Server) error {
log.Info(fmt.Sprint("Whisper started")) log.Info("Whisper started")
go self.update() go self.update()
return nil return nil
} }
@ -182,7 +182,7 @@ func (self *Whisper) Start(*p2p.Server) error {
// of the Whisper protocol. // of the Whisper protocol.
func (self *Whisper) Stop() error { func (self *Whisper) Stop() error {
close(self.quit) close(self.quit)
log.Info(fmt.Sprint("Whisper stopped")) log.Info("Whisper stopped")
return nil return nil
} }

View file

@ -222,7 +222,7 @@ func (api *PublicWhisperAPI) Subscribe(args WhisperFilterArgs) (string, error) {
var err error var err error
for i, bt := range args.Topics { for i, bt := range args.Topics {
if len(bt) == 0 || len(bt) > 4 { if len(bt) == 0 || len(bt) > 4 {
return "", errors.New(fmt.Sprintf("subscribe: topic %d has wrong size: %d", i, len(bt))) return "", fmt.Errorf("subscribe: topic %d has wrong size: %d", i, len(bt))
} }
filter.Topics = append(filter.Topics, bt) filter.Topics = append(filter.Topics, bt)
} }
@ -332,7 +332,7 @@ func (api *PublicWhisperAPI) Post(args PostArgs) error {
if len(args.Topic) == TopicLength { if len(args.Topic) == TopicLength {
params.Topic = BytesToTopic(args.Topic) params.Topic = BytesToTopic(args.Topic)
} else if len(args.Topic) != 0 { } else if len(args.Topic) != 0 {
return errors.New(fmt.Sprintf("post: wrong topic size %d", len(args.Topic))) return fmt.Errorf("post: wrong topic size %d", len(args.Topic))
} }
if args.Type == "sym" { if args.Type == "sym" {

View file

@ -284,9 +284,8 @@ func waitForMessages(api *PublicWhisperAPI, id string, target int) []*WhisperMes
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
mail := api.GetNewSubscriptionMessages(id) mail := api.GetNewSubscriptionMessages(id)
if len(mail) > 0 { if len(mail) > 0 {
for _, m := range mail { result = append(result, mail...)
result = append(result, m)
}
if len(result) >= target { if len(result) >= target {
break break
} }

View file

@ -25,11 +25,6 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
func copyFromBuf(dst []byte, src []byte, beg int) int {
copy(dst, src[beg:])
return beg + len(dst)
}
func generateMessageParams() (*MessageParams, error) { func generateMessageParams() (*MessageParams, error) {
// set all the parameters except p.Dst and p.Padding // set all the parameters except p.Dst and p.Padding
@ -158,7 +153,7 @@ func TestMessageWrap(t *testing.T) {
params.TTL = 1000000 params.TTL = 1000000
params.WorkTime = 1 params.WorkTime = 1
params.PoW = 10000000.0 params.PoW = 10000000.0
env, err = msg2.Wrap(params) _, err = msg2.Wrap(params)
if err == nil { if err == nil {
t.Fatalf("unexpectedly reached the PoW target with seed %d.", seed) t.Fatalf("unexpectedly reached the PoW target with seed %d.", seed)
} }