Merge pull request #3809 from fjl/all-use-normal-context

all: import "context" instead of "golang.org/x/net/context"
This commit is contained in:
Péter Szilágyi 2017-03-23 10:22:56 +02:00 committed by GitHub
commit 3fa0fa713b
76 changed files with 215 additions and 517 deletions

View File

@ -17,13 +17,13 @@
package bind package bind
import ( import (
"context"
"errors" "errors"
"math/big" "math/big"
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"golang.org/x/net/context"
) )
var ( var (

View File

@ -17,6 +17,7 @@
package backends package backends
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"math/big" "math/big"
@ -34,7 +35,6 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
"golang.org/x/net/context"
) )
// Default chain configuration which sets homestead phase at block 0 (i.e. no frontier) // Default chain configuration which sets homestead phase at block 0 (i.e. no frontier)

View File

@ -17,6 +17,7 @@
package bind package bind
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"math/big" "math/big"
@ -26,7 +27,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"golang.org/x/net/context"
) )
// SignerFn is a signer function callback when a contract requires a method to // SignerFn is a signer function callback when a contract requires a method to

View File

@ -17,13 +17,13 @@
package bind package bind
import ( import (
"context"
"fmt" "fmt"
"time" "time"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/net/context"
) )
// WaitMined waits for tx to be mined on the blockchain. // WaitMined waits for tx to be mined on the blockchain.

View File

@ -17,6 +17,7 @@
package bind_test package bind_test
import ( import (
"context"
"math/big" "math/big"
"testing" "testing"
"time" "time"
@ -27,7 +28,6 @@ import (
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"golang.org/x/net/context"
) )
var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")

View File

@ -21,6 +21,7 @@
package usbwallet package usbwallet
import ( import (
"context"
"encoding/binary" "encoding/binary"
"encoding/hex" "encoding/hex"
"errors" "errors"
@ -38,7 +39,6 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/karalabe/hid" "github.com/karalabe/hid"
"golang.org/x/net/context"
) )
// Maximum time between wallet health checks to detect USB unplugs. // Maximum time between wallet health checks to detect USB unplugs.

View File

@ -1,27 +0,0 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,18 +1,3 @@
# Vendored Dependencies
Dependencies are almost all vendored in at the standard Go `/vendor` path. This allows
people to build go-ethereum using the standard toolchain without any particular package
manager. It also plays nicely with `go get`, not requiring external code to be relied on.
The one single dependent package missing from `vendor` is `golang.org/x/net/context`. As
this is a package exposed via public library APIs, it must not be vendored as dependent
code woulnd't be able to instantiate.
To allow reproducible builds of go-ethereum nonetheless that don't need network access
during build time to fetch `golang.org/x/net/context`, a version was copied into our repo
at the very specific `/build/_vendor` path, which is added automatically by all CI build
scripts and the makefile too.
# Debian Packaging # Debian Packaging
Tagged releases and develop branch commits are available as installable Debian packages Tagged releases and develop branch commits are available as installable Debian packages

View File

@ -26,6 +26,7 @@ package chequebook
import ( import (
"bytes" "bytes"
"context"
"crypto/ecdsa" "crypto/ecdsa"
"encoding/json" "encoding/json"
"fmt" "fmt"
@ -43,7 +44,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/swarm/services/swap/swap" "github.com/ethereum/go-ethereum/swarm/services/swap/swap"
"golang.org/x/net/context"
) )
// TODO(zelig): watch peer solvency and notify of bouncing cheques // TODO(zelig): watch peer solvency and notify of bouncing cheques

View File

@ -20,6 +20,7 @@ package release
//go:generate abigen --sol ./contract.sol --pkg release --out ./contract.go //go:generate abigen --sol ./contract.sol --pkg release --out ./contract.go
import ( import (
"context"
"fmt" "fmt"
"strings" "strings"
"time" "time"
@ -33,7 +34,6 @@ import (
"github.com/ethereum/go-ethereum/node" "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/context"
) )
// Interval to check for new releases // Interval to check for new releases
@ -116,47 +116,49 @@ func (r *ReleaseService) checker() {
for { for {
select { select {
// If the time arrived, check for a new release
case <-timer.C: case <-timer.C:
// Rechedule the timer before continuing // Rechedule the timer before continuing
timer.Reset(releaseRecheckInterval) timer.Reset(releaseRecheckInterval)
r.checkVersion()
// Retrieve the current version, and handle missing contracts gracefully
ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
opts := &bind.CallOpts{Context: ctx}
version, err := r.oracle.CurrentVersion(opts)
if err != nil {
if err == bind.ErrNoCode {
log.Debug("Release oracle not found", "contract", r.config.Oracle)
continue
}
log.Error("Failed to retrieve current release", "err", err)
continue
}
// Version was successfully retrieved, notify if newer than ours
if version.Major > r.config.Major ||
(version.Major == r.config.Major && version.Minor > r.config.Minor) ||
(version.Major == r.config.Major && version.Minor == r.config.Minor && version.Patch > r.config.Patch) {
warning := fmt.Sprintf("Client v%d.%d.%d-%x seems older than the latest upstream release v%d.%d.%d-%x",
r.config.Major, r.config.Minor, r.config.Patch, r.config.Commit[:4], version.Major, version.Minor, version.Patch, version.Commit[:4])
howtofix := fmt.Sprintf("Please check https://github.com/ethereum/go-ethereum/releases for new releases")
separator := strings.Repeat("-", len(warning))
log.Warn(separator)
log.Warn(warning)
log.Warn(howtofix)
log.Warn(separator)
} else {
log.Debug("Client seems up to date with upstream",
"local", fmt.Sprintf("v%d.%d.%d-%x", r.config.Major, r.config.Minor, r.config.Patch, r.config.Commit[:4]),
"upstream", fmt.Sprintf("v%d.%d.%d-%x", version.Major, version.Minor, version.Patch, version.Commit[:4]))
}
// If termination was requested, return
case errc := <-r.quit: case errc := <-r.quit:
errc <- nil errc <- nil
return return
} }
} }
} }
func (r *ReleaseService) checkVersion() {
// Retrieve the current version, and handle missing contracts gracefully
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
opts := &bind.CallOpts{Context: ctx}
defer cancel()
version, err := r.oracle.CurrentVersion(opts)
if err != nil {
if err == bind.ErrNoCode {
log.Debug("Release oracle not found", "contract", r.config.Oracle)
} else {
log.Error("Failed to retrieve current release", "err", err)
}
return
}
// Version was successfully retrieved, notify if newer than ours
if version.Major > r.config.Major ||
(version.Major == r.config.Major && version.Minor > r.config.Minor) ||
(version.Major == r.config.Major && version.Minor == r.config.Minor && version.Patch > r.config.Patch) {
warning := fmt.Sprintf("Client v%d.%d.%d-%x seems older than the latest upstream release v%d.%d.%d-%x",
r.config.Major, r.config.Minor, r.config.Patch, r.config.Commit[:4], version.Major, version.Minor, version.Patch, version.Commit[:4])
howtofix := fmt.Sprintf("Please check https://github.com/ethereum/go-ethereum/releases for new releases")
separator := strings.Repeat("-", len(warning))
log.Warn(separator)
log.Warn(warning)
log.Warn(howtofix)
log.Warn(separator)
} else {
log.Debug("Client seems up to date with upstream",
"local", fmt.Sprintf("v%d.%d.%d-%x", r.config.Major, r.config.Minor, r.config.Patch, r.config.Commit[:4]),
"upstream", fmt.Sprintf("v%d.%d.%d-%x", version.Major, version.Minor, version.Patch, version.Commit[:4]))
}
}

View File

@ -19,6 +19,7 @@ package eth
import ( import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -39,7 +40,6 @@ import (
"github.com/ethereum/go-ethereum/miner" "github.com/ethereum/go-ethereum/miner"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"golang.org/x/net/context"
) )
const defaultTraceTimeout = 5 * time.Second const defaultTraceTimeout = 5 * time.Second

View File

@ -17,6 +17,7 @@
package eth package eth
import ( import (
"context"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
@ -33,7 +34,6 @@ import (
"github.com/ethereum/go-ethereum/internal/ethapi" "github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
// EthApiBackend implements ethapi.Backend for full nodes // EthApiBackend implements ethapi.Backend for full nodes

View File

@ -17,6 +17,7 @@
package eth package eth
import ( import (
"context"
"math/big" "math/big"
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
@ -26,7 +27,6 @@ import (
"github.com/ethereum/go-ethereum/internal/ethapi" "github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
// ContractBackend implements bind.ContractBackend with direct calls to Ethereum // ContractBackend implements bind.ContractBackend with direct calls to Ethereum

View File

@ -17,12 +17,12 @@
package downloader package downloader
import ( import (
"context"
"sync" "sync"
ethereum "github.com/ethereum/go-ethereum" ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
// PublicDownloaderAPI provides an API which gives information about the current synchronisation status. // PublicDownloaderAPI provides an API which gives information about the current synchronisation status.

View File

@ -17,6 +17,7 @@
package filters package filters
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -24,8 +25,6 @@ import (
"sync" "sync"
"time" "time"
"golang.org/x/net/context"
"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/core/types" "github.com/ethereum/go-ethereum/core/types"

View File

@ -17,10 +17,10 @@
package filters package filters
import ( import (
"context"
"math" "math"
"time"
"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"
@ -28,7 +28,6 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
type Backend interface { type Backend interface {

View File

@ -19,6 +19,7 @@
package filters package filters
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"sync" "sync"
@ -29,7 +30,6 @@ import (
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
// Type determines the kind of filter and is used to put the filter in to // Type determines the kind of filter and is used to put the filter in to
@ -372,7 +372,8 @@ func (es *EventSystem) lightFilterNewHead(newHeader *types.Header, callBack func
func (es *EventSystem) lightFilterLogs(header *types.Header, addresses []common.Address, topics [][]common.Hash, remove bool) []*types.Log { func (es *EventSystem) lightFilterLogs(header *types.Header, addresses []common.Address, topics [][]common.Hash, remove bool) []*types.Log {
if bloomFilter(header.Bloom, addresses, topics) { if bloomFilter(header.Bloom, addresses, topics) {
// Get the logs of the block // Get the logs of the block
ctx, _ := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
receipts, err := es.backend.GetReceipts(ctx, header.Hash()) receipts, err := es.backend.GetReceipts(ctx, header.Hash())
if err != nil { if err != nil {
return nil return nil

View File

@ -17,13 +17,12 @@
package filters package filters
import ( import (
"context"
"math/big" "math/big"
"reflect" "reflect"
"testing" "testing"
"time" "time"
"golang.org/x/net/context"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"

View File

@ -17,13 +17,12 @@
package filters package filters
import ( import (
"context"
"io/ioutil" "io/ioutil"
"math/big" "math/big"
"os" "os"
"testing" "testing"
"golang.org/x/net/context"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"

View File

@ -17,6 +17,7 @@
package gasprice package gasprice
import ( import (
"context"
"math/big" "math/big"
"sort" "sort"
"sync" "sync"
@ -24,7 +25,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/internal/ethapi" "github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
const ( const (

View File

@ -18,6 +18,7 @@
package ethclient package ethclient
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"math/big" "math/big"
@ -28,7 +29,6 @@ import (
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
// Client defines typed wrappers for the Ethereum RPC API. // Client defines typed wrappers for the Ethereum RPC API.

View File

@ -17,11 +17,11 @@
package event package event
import ( import (
"context"
"sync" "sync"
"time" "time"
"github.com/ethereum/go-ethereum/common/mclock" "github.com/ethereum/go-ethereum/common/mclock"
"golang.org/x/net/context"
) )
// Subscription represents a stream of events. The carrier of the events is typically a // Subscription represents a stream of events. The carrier of the events is typically a

View File

@ -17,11 +17,10 @@
package event package event
import ( import (
"context"
"errors" "errors"
"testing" "testing"
"time" "time"
"golang.org/x/net/context"
) )
var errInts = errors.New("error in subscribeInts") var errInts = errors.New("error in subscribeInts")

View File

@ -18,12 +18,12 @@
package ethereum package ethereum
import ( import (
"context"
"errors" "errors"
"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/core/types"
"golang.org/x/net/context"
) )
// NotFound is returned by API methods if the requested item does not exist. // NotFound is returned by API methods if the requested item does not exist.

View File

@ -52,19 +52,10 @@ func MustRunCommand(cmd string, args ...string) {
// GOPATH returns the value that the GOPATH environment // GOPATH returns the value that the GOPATH environment
// variable should be set to. // variable should be set to.
func GOPATH() string { func GOPATH() string {
path := filepath.SplitList(os.Getenv("GOPATH")) if os.Getenv("GOPATH") == "" {
if len(path) == 0 {
log.Fatal("GOPATH is not set") log.Fatal("GOPATH is not set")
} }
// Ensure that our internal vendor folder is on GOPATH return os.Getenv("GOPATH")
vendor, _ := filepath.Abs(filepath.Join("build", "_vendor"))
for _, dir := range path {
if dir == vendor {
return strings.Join(path, string(filepath.ListSeparator))
}
}
newpath := append(path[:1], append([]string{vendor}, path[1:]...)...)
return strings.Join(newpath, string(filepath.ListSeparator))
} }
// VERSION returns the content of the VERSION file. // VERSION returns the content of the VERSION file.

View File

@ -18,6 +18,7 @@ package ethapi
import ( import (
"bytes" "bytes"
"context"
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
@ -43,7 +44,6 @@ import (
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util" "github.com/syndtr/goleveldb/leveldb/util"
"golang.org/x/net/context"
) )
const ( const (

View File

@ -18,6 +18,7 @@
package ethapi package ethapi
import ( import (
"context"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
@ -30,7 +31,6 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
// Backend interface provides the common API services (that are provided by // Backend interface provides the common API services (that are provided by

View File

@ -17,6 +17,7 @@
package les package les
import ( import (
"context"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
@ -33,7 +34,6 @@ import (
"github.com/ethereum/go-ethereum/light" "github.com/ethereum/go-ethereum/light"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
type LesApiBackend struct { type LesApiBackend struct {

View File

@ -17,6 +17,7 @@
package les package les
import ( import (
"context"
"crypto/rand" "crypto/rand"
"encoding/binary" "encoding/binary"
"sync" "sync"
@ -26,7 +27,6 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/light" "github.com/ethereum/go-ethereum/light"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/net/context"
) )
var ( var (

View File

@ -18,6 +18,7 @@ package les
import ( import (
"bytes" "bytes"
"context"
"math/big" "math/big"
"testing" "testing"
"time" "time"
@ -32,7 +33,6 @@ import (
"github.com/ethereum/go-ethereum/light" "github.com/ethereum/go-ethereum/light"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"golang.org/x/net/context"
) )
type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte
@ -181,8 +181,11 @@ func testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
for i := uint64(0); i <= pm.blockchain.CurrentHeader().Number.Uint64(); i++ { for i := uint64(0); i <= pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
bhash := core.GetCanonicalHash(db, i) bhash := core.GetCanonicalHash(db, i)
b1 := fn(light.NoOdr, db, pm.chainConfig, pm.blockchain.(*core.BlockChain), nil, bhash) b1 := fn(light.NoOdr, db, pm.chainConfig, pm.blockchain.(*core.BlockChain), nil, bhash)
ctx, _ := context.WithTimeout(context.Background(), 200*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
b2 := fn(ctx, ldb, lpm.chainConfig, nil, lpm.blockchain.(*light.LightChain), bhash) b2 := fn(ctx, ldb, lpm.chainConfig, nil, lpm.blockchain.(*light.LightChain), bhash)
eq := bytes.Equal(b1, b2) eq := bytes.Equal(b1, b2)
exp := i < expFail exp := i < expFail
if exp && !eq { if exp && !eq {

View File

@ -17,6 +17,7 @@
package les package les
import ( import (
"context"
"testing" "testing"
"time" "time"
@ -25,7 +26,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/light" "github.com/ethereum/go-ethereum/light"
"golang.org/x/net/context"
) )
var testBankSecureTrieKey = secAddr(testBankAddress) var testBankSecureTrieKey = secAddr(testBankAddress)
@ -91,7 +91,9 @@ func testAccess(t *testing.T, protocol int, fn accessTestFn) {
for i := uint64(0); i <= pm.blockchain.CurrentHeader().Number.Uint64(); i++ { for i := uint64(0); i <= pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
bhash := core.GetCanonicalHash(db, i) bhash := core.GetCanonicalHash(db, i)
if req := fn(ldb, bhash, i); req != nil { if req := fn(ldb, bhash, i); req != nil {
ctx, _ := context.WithTimeout(context.Background(), 200*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
err := odr.Retrieve(ctx, req) err := odr.Retrieve(ctx, req)
got := err == nil got := err == nil
exp := i < expFail exp := i < expFail

View File

@ -17,12 +17,12 @@
package les package les
import ( import (
"context"
"time" "time"
"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/light" "github.com/ethereum/go-ethereum/light"
"golang.org/x/net/context"
) )
const ( const (
@ -77,8 +77,8 @@ func (pm *ProtocolManager) synchronise(peer *peer) {
return return
} }
ctx, _ := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
pm.blockchain.(*light.LightChain).SyncCht(ctx) pm.blockchain.(*light.LightChain).SyncCht(ctx)
pm.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync) pm.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync)
} }

View File

@ -17,6 +17,7 @@
package light package light
import ( import (
"context"
"math/big" "math/big"
"sync" "sync"
"sync/atomic" "sync/atomic"
@ -32,7 +33,6 @@ import (
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/hashicorp/golang-lru" "github.com/hashicorp/golang-lru"
"golang.org/x/net/context"
) )
var ( var (

View File

@ -17,6 +17,7 @@
package light package light
import ( import (
"context"
"fmt" "fmt"
"math/big" "math/big"
"runtime" "runtime"
@ -30,7 +31,6 @@ import (
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
"github.com/hashicorp/golang-lru" "github.com/hashicorp/golang-lru"
"golang.org/x/net/context"
) )
// So we can deterministically seed different blockchains // So we can deterministically seed different blockchains

View File

@ -19,6 +19,7 @@
package light package light
import ( import (
"context"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -27,7 +28,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"golang.org/x/net/context"
) )
// NoOdr is the default context passed to an ODR capable function when the ODR // NoOdr is the default context passed to an ODR capable function when the ODR

View File

@ -18,6 +18,7 @@ package light
import ( import (
"bytes" "bytes"
"context"
"errors" "errors"
"math/big" "math/big"
"testing" "testing"
@ -36,7 +37,6 @@ import (
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
"golang.org/x/net/context"
) )
var ( var (
@ -277,8 +277,11 @@ func testChainOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ { for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ {
bhash := core.GetCanonicalHash(sdb, i) bhash := core.GetCanonicalHash(sdb, i)
b1 := fn(NoOdr, sdb, blockchain, nil, bhash) b1 := fn(NoOdr, sdb, blockchain, nil, bhash)
ctx, _ := context.WithTimeout(context.Background(), 200*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
b2 := fn(ctx, ldb, nil, lightchain, bhash) b2 := fn(ctx, ldb, nil, lightchain, bhash)
eq := bytes.Equal(b1, b2) eq := bytes.Equal(b1, b2)
exp := i < expFail exp := i < expFail
if exp && !eq { if exp && !eq {

View File

@ -18,6 +18,7 @@ package light
import ( import (
"bytes" "bytes"
"context"
"errors" "errors"
"math/big" "math/big"
@ -27,7 +28,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"golang.org/x/net/context"
) )
var sha3_nil = crypto.Keccak256Hash(nil) var sha3_nil = crypto.Keccak256Hash(nil)

View File

@ -17,11 +17,11 @@
package light package light
import ( import (
"context"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"golang.org/x/net/context"
) )
// LightState is a memory representation of a state. // LightState is a memory representation of a state.

View File

@ -18,13 +18,13 @@ package light
import ( import (
"bytes" "bytes"
"context"
"fmt" "fmt"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"golang.org/x/net/context"
) )
var emptyCodeHash = crypto.Keccak256(nil) var emptyCodeHash = crypto.Keccak256(nil)

View File

@ -18,6 +18,7 @@ package light
import ( import (
"bytes" "bytes"
"context"
"math/big" "math/big"
"testing" "testing"
@ -26,7 +27,6 @@ import (
"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"
"golang.org/x/net/context"
) )
func makeTestState() (common.Hash, ethdb.Database) { func makeTestState() (common.Hash, ethdb.Database) {

View File

@ -17,9 +17,10 @@
package light package light
import ( import (
"context"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
"golang.org/x/net/context"
) )
// LightTrie is an ODR-capable wrapper around trie.SecureTrie // LightTrie is an ODR-capable wrapper around trie.SecureTrie

View File

@ -17,6 +17,7 @@
package light package light
import ( import (
"context"
"fmt" "fmt"
"sync" "sync"
"time" "time"
@ -29,7 +30,6 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"golang.org/x/net/context"
) )
// txPermanent is the number of mined blocks after a mined transaction is // txPermanent is the number of mined blocks after a mined transaction is
@ -230,13 +230,13 @@ func (pool *TxPool) rollbackTxs(hash common.Hash, txc txStateChanges) {
} }
} }
// setNewHead sets a new head header, processing (and rolling back if necessary) // reorgOnNewHead sets a new head header, processing (and rolling back if necessary)
// the blocks since the last known head and returns a txStateChanges map containing // the blocks since the last known head and returns a txStateChanges map containing
// the recently mined and rolled back transaction hashes. If an error (context // the recently mined and rolled back transaction hashes. If an error (context
// timeout) occurs during checking new blocks, it leaves the locally known head // timeout) occurs during checking new blocks, it leaves the locally known head
// at the latest checked block and still returns a valid txStateChanges, making it // at the latest checked block and still returns a valid txStateChanges, making it
// possible to continue checking the missing blocks at the next chain head event // possible to continue checking the missing blocks at the next chain head event
func (pool *TxPool) setNewHead(ctx context.Context, newHeader *types.Header) (txStateChanges, error) { func (pool *TxPool) reorgOnNewHead(ctx context.Context, newHeader *types.Header) (txStateChanges, error) {
txc := make(txStateChanges) txc := make(txStateChanges)
oldh := pool.chain.GetHeaderByHash(pool.head) oldh := pool.chain.GetHeaderByHash(pool.head)
newh := newHeader newh := newHeader
@ -305,20 +305,28 @@ func (pool *TxPool) eventLoop() {
for ev := range pool.events.Chan() { for ev := range pool.events.Chan() {
switch ev.Data.(type) { switch ev.Data.(type) {
case core.ChainHeadEvent: case core.ChainHeadEvent:
head := pool.chain.CurrentHeader() pool.setNewHead(ev.Data.(core.ChainHeadEvent).Block.Header())
pool.mu.Lock() // hack in order to avoid hogging the lock; this part will
ctx, _ := context.WithTimeout(context.Background(), blockCheckTimeout) // be replaced by a subsequent PR.
txc, _ := pool.setNewHead(ctx, head) time.Sleep(time.Millisecond)
m, r := txc.getLists()
pool.relay.NewHead(pool.head, m, r)
pool.homestead = pool.config.IsHomestead(head.Number)
pool.signer = types.MakeSigner(pool.config, head.Number)
pool.mu.Unlock()
time.Sleep(time.Millisecond) // hack in order to avoid hogging the lock; this part will be replaced by a subsequent PR
} }
} }
} }
func (pool *TxPool) setNewHead(head *types.Header) {
pool.mu.Lock()
defer pool.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), blockCheckTimeout)
defer cancel()
txc, _ := pool.reorgOnNewHead(ctx, head)
m, r := txc.getLists()
pool.relay.NewHead(pool.head, m, r)
pool.homestead = pool.config.IsHomestead(head.Number)
pool.signer = types.MakeSigner(pool.config, head.Number)
}
// Stop stops the light transaction pool // Stop stops the light transaction pool
func (pool *TxPool) Stop() { func (pool *TxPool) Stop() {
close(pool.quit) close(pool.quit)

View File

@ -17,6 +17,7 @@
package light package light
import ( import (
"context"
"math" "math"
"math/big" "math/big"
"testing" "testing"
@ -30,7 +31,6 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
"golang.org/x/net/context"
) )
type testTxRelay struct { type testTxRelay struct {
@ -107,10 +107,11 @@ func TestTxPool(t *testing.T) {
lightchain.SetValidator(bproc{}) lightchain.SetValidator(bproc{})
txPermanent = 50 txPermanent = 50
pool := NewTxPool(testChainConfig(), evmux, lightchain, relay) pool := NewTxPool(testChainConfig(), evmux, lightchain, relay)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
for ii, block := range gchain { for ii, block := range gchain {
i := ii + 1 i := ii + 1
ctx, _ := context.WithTimeout(context.Background(), 200*time.Millisecond)
s := sentTx(i - 1) s := sentTx(i - 1)
e := sentTx(i) e := sentTx(i)
for i := s; i < e; i++ { for i := s; i < e; i++ {

View File

@ -17,12 +17,12 @@
package light package light
import ( import (
"context"
"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/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"golang.org/x/net/context"
) )
// VMState is a wrapper for the light state that holds the actual context and // VMState is a wrapper for the light state that holds the actual context and

View File

@ -93,3 +93,8 @@ func (bi *BigInts) Set(index int, bigint *BigInt) error {
bi.bigints[index] = bigint.bigint bi.bigints[index] = bigint.bigint
return nil return nil
} }
// GetString returns the value of x as a formatted string in some number base.
func (bi *BigInt) GetString(base int) string {
return bi.bigint.Text(base)
}

View File

@ -1,26 +0,0 @@
// Copyright 2016 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/>.
// Contains the wrappers from the math/big package that require Go 1.7 and above.
// +build go1.7
package geth
// GetString returns the value of x as a formatted string in some number base.
func (bi *BigInt) GetString(base int) string {
return bi.bigint.Text(base)
}

View File

@ -20,9 +20,8 @@
package geth package geth
import ( import (
"context"
"time" "time"
"golang.org/x/net/context"
) )
// Context carries a deadline, a cancelation signal, and other values across API // Context carries a deadline, a cancelation signal, and other values across API

View File

@ -19,6 +19,7 @@ package rpc
import ( import (
"bytes" "bytes"
"container/list" "container/list"
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -31,7 +32,6 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/net/context"
) )
var ( var (

View File

@ -1,60 +0,0 @@
// Copyright 2016 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/>.
// +build !go1.5
package rpc
import (
"net"
"net/http"
"time"
"golang.org/x/net/context"
)
// In older versions of Go (below 1.5), dials cannot be canceled
// via a channel or context. The context deadline can still applied.
// contextDialer returns a dialer that applies the deadline value from the given context.
func contextDialer(ctx context.Context) *net.Dialer {
dialer := &net.Dialer{KeepAlive: tcpKeepAliveInterval}
if deadline, ok := ctx.Deadline(); ok {
dialer.Deadline = deadline
} else {
dialer.Deadline = time.Now().Add(defaultDialTimeout)
}
return dialer
}
// dialContext connects to the given address, aborting the dial if ctx is canceled.
func dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
return contextDialer(ctx).Dial(network, addr)
}
// requestWithContext copies req, adding the cancelation channel and deadline from ctx.
func requestWithContext(c *http.Client, req *http.Request, ctx context.Context) (*http.Client, *http.Request) {
// Set Timeout on the client if the context has a deadline.
// Note that there is no default timeout (unlike in contextDialer) because
// the timeout applies to the entire request, including reads from body.
if deadline, ok := ctx.Deadline(); ok {
c2 := *c
c2.Timeout = deadline.Sub(time.Now())
c = &c2
}
req2 := *req
return c, &req2
}

View File

@ -1,61 +0,0 @@
// Copyright 2016 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/>.
// +build go1.5,!go1.6
package rpc
import (
"net"
"net/http"
"time"
"golang.org/x/net/context"
)
// In Go 1.5, dials cannot be canceled via a channel or context. The context deadline can
// still be applied. Go 1.5 adds the ability to cancel HTTP requests via a channel.
// contextDialer returns a dialer that applies the deadline value from the given context.
func contextDialer(ctx context.Context) *net.Dialer {
dialer := &net.Dialer{KeepAlive: tcpKeepAliveInterval}
if deadline, ok := ctx.Deadline(); ok {
dialer.Deadline = deadline
} else {
dialer.Deadline = time.Now().Add(defaultDialTimeout)
}
return dialer
}
// dialContext connects to the given address, aborting the dial if ctx is canceled.
func dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
return contextDialer(ctx).Dial(network, addr)
}
// requestWithContext copies req, adding the cancelation channel and deadline from ctx.
func requestWithContext(c *http.Client, req *http.Request, ctx context.Context) (*http.Client, *http.Request) {
// Set Timeout on the client if the context has a deadline.
// Note that there is no default timeout (unlike in contextDialer) because
// the timeout applies to the entire request, including reads from body.
if deadline, ok := ctx.Deadline(); ok {
c2 := *c
c2.Timeout = deadline.Sub(time.Now())
c = &c2
}
req2 := *req
req2.Cancel = ctx.Done()
return c, &req2
}

View File

@ -1,55 +0,0 @@
// Copyright 2016 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/>.
// +build go1.6,!go1.7
package rpc
import (
"net"
"net/http"
"time"
"golang.org/x/net/context"
)
// In Go 1.6, net.Dialer gained the ability to cancel via a channel.
// contextDialer returns a dialer that applies the deadline value from the given context.
func contextDialer(ctx context.Context) *net.Dialer {
dialer := &net.Dialer{Cancel: ctx.Done(), KeepAlive: tcpKeepAliveInterval}
if deadline, ok := ctx.Deadline(); ok {
dialer.Deadline = deadline
} else {
dialer.Deadline = time.Now().Add(defaultDialTimeout)
}
return dialer
}
// dialContext connects to the given address, aborting the dial if ctx is canceled.
func dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
return contextDialer(ctx).Dial(network, addr)
}
// requestWithContext copies req, adding the cancelation channel and deadline from ctx.
func requestWithContext(c *http.Client, req *http.Request, ctx context.Context) (*http.Client, *http.Request) {
// We set Timeout on the client for Go <= 1.5. There
// is no need to do that here because the dial will be canceled
// by package http.
req2 := *req
req2.Cancel = ctx.Done()
return c, &req2
}

View File

@ -1,51 +0,0 @@
// Copyright 2016 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/>.
// +build go1.7
package rpc
import (
"context"
"net"
"net/http"
"time"
)
// In Go 1.7, context moved into the standard library and support
// for cancelation via context was added to net.Dialer and http.Request.
// contextDialer returns a dialer that applies the deadline value from the given context.
func contextDialer(ctx context.Context) *net.Dialer {
dialer := &net.Dialer{Cancel: ctx.Done(), KeepAlive: tcpKeepAliveInterval}
if deadline, ok := ctx.Deadline(); ok {
dialer.Deadline = deadline
} else {
dialer.Deadline = time.Now().Add(defaultDialTimeout)
}
return dialer
}
// dialContext connects to the given address, aborting the dial if ctx is canceled.
func dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
d := &net.Dialer{KeepAlive: tcpKeepAliveInterval}
return d.DialContext(ctx, network, addr)
}
// requestWithContext copies req, adding the cancelation channel and deadline from ctx.
func requestWithContext(c *http.Client, req *http.Request, ctx context.Context) (*http.Client, *http.Request) {
return c, req.WithContext(ctx)
}

View File

@ -17,12 +17,12 @@
package rpc_test package rpc_test
import ( import (
"context"
"fmt" "fmt"
"math/big" "math/big"
"time" "time"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"golang.org/x/net/context"
) )
// In this example, our client whishes to track the latest 'block number' // In this example, our client whishes to track the latest 'block number'

View File

@ -17,6 +17,7 @@
package rpc package rpc
import ( import (
"context"
"fmt" "fmt"
"math/rand" "math/rand"
"net" "net"
@ -31,7 +32,6 @@ import (
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/net/context"
) )
func TestClientRequest(t *testing.T) { func TestClientRequest(t *testing.T) {

View File

@ -18,6 +18,7 @@ package rpc
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@ -29,7 +30,6 @@ import (
"time" "time"
"github.com/rs/cors" "github.com/rs/cors"
"golang.org/x/net/context"
) )
const ( const (
@ -115,11 +115,11 @@ func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadClos
if err != nil { if err != nil {
return nil, err return nil, err
} }
client, req := requestWithContext(hc.client, hc.req, ctx) req := hc.req.WithContext(ctx)
req.Body = ioutil.NopCloser(bytes.NewReader(body)) req.Body = ioutil.NopCloser(bytes.NewReader(body))
req.ContentLength = int64(len(body)) req.ContentLength = int64(len(body))
resp, err := client.Do(req) resp, err := hc.client.Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -17,9 +17,8 @@
package rpc package rpc
import ( import (
"context"
"net" "net"
"golang.org/x/net/context"
) )
// NewInProcClient attaches an in-process connection to the given RPC server. // NewInProcClient attaches an in-process connection to the given RPC server.

View File

@ -17,12 +17,11 @@
package rpc package rpc
import ( import (
"context"
"fmt" "fmt"
"net" "net"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/net/context"
) )
// CreateIPCListener creates an listener, on Unix platforms this is a unix socket, on // CreateIPCListener creates an listener, on Unix platforms this is a unix socket, on

View File

@ -19,11 +19,10 @@
package rpc package rpc
import ( import (
"context"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"golang.org/x/net/context"
) )
// ipcListen will create a Unix socket on the given endpoint. // ipcListen will create a Unix socket on the given endpoint.

View File

@ -19,10 +19,10 @@
package rpc package rpc
import ( import (
"context"
"net" "net"
"time" "time"
"golang.org/x/net/context"
"gopkg.in/natefinch/npipe.v2" "gopkg.in/natefinch/npipe.v2"
) )

View File

@ -17,14 +17,13 @@
package rpc package rpc
import ( import (
"context"
"fmt" "fmt"
"reflect" "reflect"
"runtime" "runtime"
"sync/atomic" "sync/atomic"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/net/context"
"gopkg.in/fatih/set.v0" "gopkg.in/fatih/set.v0"
) )

View File

@ -17,13 +17,12 @@
package rpc package rpc
import ( import (
"context"
"encoding/json" "encoding/json"
"net" "net"
"reflect" "reflect"
"testing" "testing"
"time" "time"
"golang.org/x/net/context"
) )
type Service struct{} type Service struct{}

View File

@ -17,10 +17,9 @@
package rpc package rpc
import ( import (
"context"
"errors" "errors"
"sync" "sync"
"golang.org/x/net/context"
) )
var ( var (

View File

@ -17,13 +17,12 @@
package rpc package rpc
import ( import (
"context"
"encoding/json" "encoding/json"
"net" "net"
"sync" "sync"
"testing" "testing"
"time" "time"
"golang.org/x/net/context"
) )
type NotificationTestService struct { type NotificationTestService struct {

View File

@ -18,6 +18,7 @@ package rpc
import ( import (
"bufio" "bufio"
"context"
crand "crypto/rand" crand "crypto/rand"
"encoding/binary" "encoding/binary"
"encoding/hex" "encoding/hex"
@ -29,8 +30,6 @@ import (
"time" "time"
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
"golang.org/x/net/context"
) )
var ( var (

View File

@ -17,6 +17,7 @@
package rpc package rpc
import ( import (
"context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"net" "net"
@ -24,10 +25,9 @@ import (
"net/url" "net/url"
"os" "os"
"strings" "strings"
"time"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/net/context"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
"gopkg.in/fatih/set.v0" "gopkg.in/fatih/set.v0"
) )
@ -150,3 +150,18 @@ func wsDialAddress(location *url.URL) string {
} }
return location.Host return location.Host
} }
func dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
d := &net.Dialer{KeepAlive: tcpKeepAliveInterval}
return d.DialContext(ctx, network, addr)
}
func contextDialer(ctx context.Context) *net.Dialer {
dialer := &net.Dialer{Cancel: ctx.Done(), KeepAlive: tcpKeepAliveInterval}
if deadline, ok := ctx.Deadline(); ok {
dialer.Deadline = deadline
} else {
dialer.Deadline = time.Now().Add(defaultDialTimeout)
}
return dialer
}

View File

@ -17,6 +17,7 @@
package swap package swap
import ( import (
"context"
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
"math/big" "math/big"
@ -33,7 +34,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/swarm/services/swap/swap" "github.com/ethereum/go-ethereum/swarm/services/swap/swap"
"golang.org/x/net/context"
) )
// SwAP Swarm Accounting Protocol with // SwAP Swarm Accounting Protocol with

View File

@ -18,6 +18,7 @@ package swarm
import ( import (
"bytes" "bytes"
"context"
"crypto/ecdsa" "crypto/ecdsa"
"fmt" "fmt"
@ -35,7 +36,6 @@ import (
httpapi "github.com/ethereum/go-ethereum/swarm/api/http" httpapi "github.com/ethereum/go-ethereum/swarm/api/http"
"github.com/ethereum/go-ethereum/swarm/network" "github.com/ethereum/go-ethereum/swarm/network"
"github.com/ethereum/go-ethereum/swarm/storage" "github.com/ethereum/go-ethereum/swarm/storage"
"golang.org/x/net/context"
) )
// the swarm stack // the swarm stack

View File

@ -377,7 +377,7 @@ func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
if len(allKeys) < 2 || r.Intn(100) < 10 { if len(allKeys) < 2 || r.Intn(100) < 10 {
// new key // new key
key := make([]byte, r.Intn(50)) key := make([]byte, r.Intn(50))
randRead(r, key) r.Read(key)
allKeys = append(allKeys, key) allKeys = append(allKeys, key)
return key return key
} }
@ -401,22 +401,6 @@ func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
return reflect.ValueOf(steps) return reflect.ValueOf(steps)
} }
// rand.Rand provides a Read method in Go 1.7 and later, but
// we can't use it yet.
func randRead(r *rand.Rand, b []byte) {
pos := 0
val := 0
for n := 0; n < len(b); n++ {
if pos == 0 {
val = r.Int()
pos = 7
}
b[n] = byte(val)
val >>= 8
pos--
}
}
func runRandTest(rt randTest) bool { func runRandTest(rt randTest) bool {
db, _ := ethdb.NewMemDatabase() db, _ := ethdb.NewMemDatabase()
tr, _ := New(common.Hash{}, db) tr, _ := New(common.Hash{}, db)

View File

@ -7,7 +7,7 @@
// and between processes. // and between processes.
// //
// Incoming requests to a server should create a Context, and outgoing calls to // Incoming requests to a server should create a Context, and outgoing calls to
// servers should accept a Context. The chain of function calls between must // servers should accept a Context. The chain of function calls between must
// propagate the Context, optionally replacing it with a modified copy created // propagate the Context, optionally replacing it with a modified copy created
// using WithDeadline, WithTimeout, WithCancel, or WithValue. // using WithDeadline, WithTimeout, WithCancel, or WithValue.
// //
@ -16,14 +16,14 @@
// propagation: // propagation:
// //
// Do not store Contexts inside a struct type; instead, pass a Context // Do not store Contexts inside a struct type; instead, pass a Context
// explicitly to each function that needs it. The Context should be the first // explicitly to each function that needs it. The Context should be the first
// parameter, typically named ctx: // parameter, typically named ctx:
// //
// func DoSomething(ctx context.Context, arg Arg) error { // func DoSomething(ctx context.Context, arg Arg) error {
// // ... use ctx ... // // ... use ctx ...
// } // }
// //
// Do not pass a nil Context, even if a function permits it. Pass context.TODO // Do not pass a nil Context, even if a function permits it. Pass context.TODO
// if you are unsure about which Context to use. // if you are unsure about which Context to use.
// //
// Use context Values only for request-scoped data that transits processes and // Use context Values only for request-scoped data that transits processes and
@ -44,13 +44,13 @@ import "time"
// Context's methods may be called by multiple goroutines simultaneously. // Context's methods may be called by multiple goroutines simultaneously.
type Context interface { type Context interface {
// Deadline returns the time when work done on behalf of this context // Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is // should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results. // set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool) Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this // Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can // context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value. // never be canceled. Successive calls to Done return the same value.
// //
// WithCancel arranges for Done to be closed when cancel is called; // WithCancel arranges for Done to be closed when cancel is called;
// WithDeadline arranges for Done to be closed when the deadline // WithDeadline arranges for Done to be closed when the deadline
@ -79,24 +79,24 @@ type Context interface {
// a Done channel for cancelation. // a Done channel for cancelation.
Done() <-chan struct{} Done() <-chan struct{}
// Err returns a non-nil error value after Done is closed. Err returns // Err returns a non-nil error value after Done is closed. Err returns
// Canceled if the context was canceled or DeadlineExceeded if the // Canceled if the context was canceled or DeadlineExceeded if the
// context's deadline passed. No other values for Err are defined. // context's deadline passed. No other values for Err are defined.
// After Done is closed, successive calls to Err return the same value. // After Done is closed, successive calls to Err return the same value.
Err() error Err() error
// Value returns the value associated with this context for key, or nil // Value returns the value associated with this context for key, or nil
// if no value is associated with key. Successive calls to Value with // if no value is associated with key. Successive calls to Value with
// the same key returns the same result. // the same key returns the same result.
// //
// Use context values only for request-scoped data that transits // Use context values only for request-scoped data that transits
// processes and API boundaries, not for passing optional parameters to // processes and API boundaries, not for passing optional parameters to
// functions. // functions.
// //
// A key identifies a specific value in a Context. Functions that wish // A key identifies a specific value in a Context. Functions that wish
// to store values in Context typically allocate a key in a global // to store values in Context typically allocate a key in a global
// variable then use that key as the argument to context.WithValue and // variable then use that key as the argument to context.WithValue and
// Context.Value. A key can be any type that supports equality; // Context.Value. A key can be any type that supports equality;
// packages should define keys as an unexported type to avoid // packages should define keys as an unexported type to avoid
// collisions. // collisions.
// //
@ -115,7 +115,7 @@ type Context interface {
// // This prevents collisions with keys defined in other packages. // // This prevents collisions with keys defined in other packages.
// type key int // type key int
// //
// // userKey is the key for user.User values in Contexts. It is // // userKey is the key for user.User values in Contexts. It is
// // unexported; clients use user.NewContext and user.FromContext // // unexported; clients use user.NewContext and user.FromContext
// // instead of using this key directly. // // instead of using this key directly.
// var userKey key = 0 // var userKey key = 0
@ -134,14 +134,14 @@ type Context interface {
} }
// Background returns a non-nil, empty Context. It is never canceled, has no // Background returns a non-nil, empty Context. It is never canceled, has no
// values, and has no deadline. It is typically used by the main function, // values, and has no deadline. It is typically used by the main function,
// initialization, and tests, and as the top-level Context for incoming // initialization, and tests, and as the top-level Context for incoming
// requests. // requests.
func Background() Context { func Background() Context {
return background return background
} }
// TODO returns a non-nil, empty Context. Code should use context.TODO when // TODO returns a non-nil, empty Context. Code should use context.TODO when
// it's unclear which Context to use or it is not yet available (because the // it's unclear which Context to use or it is not yet available (because the
// surrounding function has not yet been extended to accept a Context // surrounding function has not yet been extended to accept a Context
// parameter). TODO is recognized by static analysis tools that determine // parameter). TODO is recognized by static analysis tools that determine

View File

@ -35,8 +35,8 @@ func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
} }
// WithDeadline returns a copy of the parent context with the deadline adjusted // WithDeadline returns a copy of the parent context with the deadline adjusted
// to be no later than d. If the parent's deadline is already earlier than d, // to be no later than d. If the parent's deadline is already earlier than d,
// WithDeadline(parent, d) is semantically equivalent to parent. The returned // WithDeadline(parent, d) is semantically equivalent to parent. The returned
// context's Done channel is closed when the deadline expires, when the returned // context's Done channel is closed when the deadline expires, when the returned
// cancel function is called, or when the parent context's Done channel is // cancel function is called, or when the parent context's Done channel is
// closed, whichever happens first. // closed, whichever happens first.

View File

@ -13,7 +13,7 @@ import (
"time" "time"
) )
// An emptyCtx is never canceled, has no values, and has no deadline. It is not // An emptyCtx is never canceled, has no values, and has no deadline. It is not
// struct{}, since vars of this type must have distinct addresses. // struct{}, since vars of this type must have distinct addresses.
type emptyCtx int type emptyCtx int
@ -104,7 +104,7 @@ func propagateCancel(parent Context, child canceler) {
} }
// parentCancelCtx follows a chain of parent references until it finds a // parentCancelCtx follows a chain of parent references until it finds a
// *cancelCtx. This function understands how each of the concrete types in this // *cancelCtx. This function understands how each of the concrete types in this
// package represents its parent. // package represents its parent.
func parentCancelCtx(parent Context) (*cancelCtx, bool) { func parentCancelCtx(parent Context) (*cancelCtx, bool) {
for { for {
@ -134,14 +134,14 @@ func removeChild(parent Context, child canceler) {
p.mu.Unlock() p.mu.Unlock()
} }
// A canceler is a context type that can be canceled directly. The // A canceler is a context type that can be canceled directly. The
// implementations are *cancelCtx and *timerCtx. // implementations are *cancelCtx and *timerCtx.
type canceler interface { type canceler interface {
cancel(removeFromParent bool, err error) cancel(removeFromParent bool, err error)
Done() <-chan struct{} Done() <-chan struct{}
} }
// A cancelCtx can be canceled. When canceled, it also cancels any children // A cancelCtx can be canceled. When canceled, it also cancels any children
// that implement canceler. // that implement canceler.
type cancelCtx struct { type cancelCtx struct {
Context Context
@ -193,8 +193,8 @@ func (c *cancelCtx) cancel(removeFromParent bool, err error) {
} }
// WithDeadline returns a copy of the parent context with the deadline adjusted // WithDeadline returns a copy of the parent context with the deadline adjusted
// to be no later than d. If the parent's deadline is already earlier than d, // to be no later than d. If the parent's deadline is already earlier than d,
// WithDeadline(parent, d) is semantically equivalent to parent. The returned // WithDeadline(parent, d) is semantically equivalent to parent. The returned
// context's Done channel is closed when the deadline expires, when the returned // context's Done channel is closed when the deadline expires, when the returned
// cancel function is called, or when the parent context's Done channel is // cancel function is called, or when the parent context's Done channel is
// closed, whichever happens first. // closed, whichever happens first.
@ -226,8 +226,8 @@ func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
return c, func() { c.cancel(true, Canceled) } return c, func() { c.cancel(true, Canceled) }
} }
// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
// implement Done and Err. It implements cancel by stopping its timer then // implement Done and Err. It implements cancel by stopping its timer then
// delegating to cancelCtx.cancel. // delegating to cancelCtx.cancel.
type timerCtx struct { type timerCtx struct {
*cancelCtx *cancelCtx
@ -281,7 +281,7 @@ func WithValue(parent Context, key interface{}, val interface{}) Context {
return &valueCtx{parent, key, val} return &valueCtx{parent, key, val}
} }
// A valueCtx carries a key-value pair. It implements Value for that key and // A valueCtx carries a key-value pair. It implements Value for that key and
// delegates all other calls to the embedded Context. // delegates all other calls to the embedded Context.
type valueCtx struct { type valueCtx struct {
Context Context

8
vendor/vendor.json vendored
View File

@ -1,6 +1,6 @@
{ {
"comment": "", "comment": "",
"ignore": "test golang.org/x/net/context", "ignore": "test",
"package": [ "package": [
{ {
"checksumSHA1": "M30X+Wqn7AnUr1numUOkQRI7ET0=", "checksumSHA1": "M30X+Wqn7AnUr1numUOkQRI7ET0=",
@ -383,6 +383,12 @@
"revision": "453249f01cfeb54c3d549ddb75ff152ca243f9d8", "revision": "453249f01cfeb54c3d549ddb75ff152ca243f9d8",
"revisionTime": "2017-02-08T20:51:15Z" "revisionTime": "2017-02-08T20:51:15Z"
}, },
{
"checksumSHA1": "Y+HGqEkYM15ir+J93MEaHdyFy0c=",
"path": "golang.org/x/net/context",
"revision": "a6577fac2d73be281a500b310739095313165611",
"revisionTime": "2017-03-08T20:54:49Z"
},
{ {
"checksumSHA1": "vqc3a+oTUGX8PmD0TS+qQ7gmN8I=", "checksumSHA1": "vqc3a+oTUGX8PmD0TS+qQ7gmN8I=",
"path": "golang.org/x/net/html", "path": "golang.org/x/net/html",

View File

@ -18,7 +18,7 @@ package whisperv5
import ( import (
"math/big" "math/big"
"math/rand" mrand "math/rand"
"testing" "testing"
"time" "time"
@ -33,12 +33,12 @@ var seed int64
// reproduciblity independent of their sequence. // reproduciblity independent of their sequence.
func InitSingleTest() { func InitSingleTest() {
seed = time.Now().Unix() seed = time.Now().Unix()
rand.Seed(seed) mrand.Seed(seed)
} }
func InitDebugTest(i int64) { func InitDebugTest(i int64) {
seed = i seed = i
rand.Seed(seed) mrand.Seed(seed)
} }
type FilterTestCase struct { type FilterTestCase struct {
@ -55,7 +55,7 @@ func generateFilter(t *testing.T, symmetric bool) (*Filter, error) {
const topicNum = 8 const topicNum = 8
f.Topics = make([]TopicType, topicNum) f.Topics = make([]TopicType, topicNum)
for i := 0; i < topicNum; i++ { for i := 0; i < topicNum; i++ {
randomize(f.Topics[i][:]) mrand.Read(f.Topics[i][:])
f.Topics[i][0] = 0x01 f.Topics[i][0] = 0x01
} }
@ -68,7 +68,7 @@ func generateFilter(t *testing.T, symmetric bool) (*Filter, error) {
if symmetric { if symmetric {
f.KeySym = make([]byte, 12) f.KeySym = make([]byte, 12)
randomize(f.KeySym) mrand.Read(f.KeySym)
f.SymKeyHash = crypto.Keccak256Hash(f.KeySym) f.SymKeyHash = crypto.Keccak256Hash(f.KeySym)
} else { } else {
f.KeyAsym, err = crypto.GenerateKey() f.KeyAsym, err = crypto.GenerateKey()
@ -87,7 +87,7 @@ func generateTestCases(t *testing.T, SizeTestFilters int) []FilterTestCase {
for i := 0; i < SizeTestFilters; i++ { for i := 0; i < SizeTestFilters; i++ {
f, _ := generateFilter(t, true) f, _ := generateFilter(t, true)
cases[i].f = f cases[i].f = f
cases[i].alive = (rand.Int()&int(1) == 0) cases[i].alive = (mrand.Int()&int(1) == 0)
} }
return cases return cases
} }
@ -147,7 +147,7 @@ func TestComparePubKey(t *testing.T) {
} }
// generate key3 == key1 // generate key3 == key1
rand.Seed(seed) mrand.Seed(seed)
key3, err := crypto.GenerateKey() key3, err := crypto.GenerateKey()
if err != nil { if err != nil {
t.Fatalf("failed to generate third key with seed %d: %s.", seed, err) t.Fatalf("failed to generate third key with seed %d: %s.", seed, err)
@ -193,7 +193,7 @@ func TestMatchEnvelope(t *testing.T) {
} }
// encrypt symmetrically // encrypt symmetrically
i := rand.Int() % 4 i := mrand.Int() % 4
fsym.Topics[i] = params.Topic fsym.Topics[i] = params.Topic
fasym.Topics[i] = params.Topic fasym.Topics[i] = params.Topic
msg = NewSentMessage(params) msg = NewSentMessage(params)
@ -544,7 +544,7 @@ func TestWatchers(t *testing.T) {
var envelopes [NumMessages]*Envelope var envelopes [NumMessages]*Envelope
for i = 0; i < NumMessages; i++ { for i = 0; i < NumMessages; i++ {
j = rand.Uint32() % NumFilters j = mrand.Uint32() % NumFilters
e = generateCompatibeEnvelope(t, tst[j].f) e = generateCompatibeEnvelope(t, tst[j].f)
envelopes[i] = e envelopes[i] = e
tst[j].msgCnt++ tst[j].msgCnt++
@ -597,7 +597,7 @@ func TestWatchers(t *testing.T) {
envelopes[0] = e envelopes[0] = e
tst[0].msgCnt++ tst[0].msgCnt++
for i = 1; i < NumMessages; i++ { for i = 1; i < NumMessages; i++ {
j = rand.Uint32() % NumFilters j = mrand.Uint32() % NumFilters
e = generateCompatibeEnvelope(t, tst[j].f) e = generateCompatibeEnvelope(t, tst[j].f)
envelopes[i] = e envelopes[i] = e
tst[j].msgCnt++ tst[j].msgCnt++

View File

@ -128,7 +128,7 @@ func (msg *SentMessage) appendPadding(params *MessageParams) {
panic("please fix the padding algorithm before releasing new version") panic("please fix the padding algorithm before releasing new version")
} }
buf := make([]byte, padSize) buf := make([]byte, padSize)
randomize(buf[1:]) mrand.Read(buf[1:])
buf[0] = byte(padSize) buf[0] = byte(padSize)
if params.Padding != nil { if params.Padding != nil {
copy(buf[1:], params.Padding) copy(buf[1:], params.Padding)
@ -365,19 +365,3 @@ func (msg *ReceivedMessage) hash() []byte {
} }
return crypto.Keccak256(msg.Raw) return crypto.Keccak256(msg.Raw)
} }
// rand.Rand provides a Read method in Go 1.7 and later,
// but we can't use it yet.
func randomize(b []byte) {
cnt := 0
val := mrand.Int63()
for n := 0; n < len(b); n++ {
b[n] = byte(val)
val >>= 8
cnt++
if cnt >= 7 {
cnt = 0
val = mrand.Int63()
}
}
}

View File

@ -18,7 +18,7 @@ package whisperv5
import ( import (
"bytes" "bytes"
"math/rand" mrand "math/rand"
"testing" "testing"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
@ -34,13 +34,13 @@ func generateMessageParams() (*MessageParams, error) {
// set all the parameters except p.Dst // set all the parameters except p.Dst
buf := make([]byte, 1024) buf := make([]byte, 1024)
randomize(buf) mrand.Read(buf)
sz := rand.Intn(400) sz := mrand.Intn(400)
var p MessageParams var p MessageParams
p.PoW = 0.01 p.PoW = 0.01
p.WorkTime = 1 p.WorkTime = 1
p.TTL = uint32(rand.Intn(1024)) p.TTL = uint32(mrand.Intn(1024))
p.Payload = make([]byte, sz) p.Payload = make([]byte, sz)
p.Padding = make([]byte, padSizeLimitUpper) p.Padding = make([]byte, padSizeLimitUpper)
p.KeySym = make([]byte, aesKeyLength) p.KeySym = make([]byte, aesKeyLength)
@ -132,7 +132,7 @@ func TestMessageEncryption(t *testing.T) {
func TestMessageWrap(t *testing.T) { func TestMessageWrap(t *testing.T) {
seed = int64(1777444222) seed = int64(1777444222)
rand.Seed(seed) mrand.Seed(seed)
target := 128.0 target := 128.0
params, err := generateMessageParams() params, err := generateMessageParams()
@ -168,7 +168,7 @@ func TestMessageWrap(t *testing.T) {
func TestMessageSeal(t *testing.T) { func TestMessageSeal(t *testing.T) {
// this test depends on deterministic choice of seed (1976726903) // this test depends on deterministic choice of seed (1976726903)
seed = int64(1976726903) seed = int64(1976726903)
rand.Seed(seed) mrand.Seed(seed)
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
@ -179,8 +179,8 @@ func TestMessageSeal(t *testing.T) {
params.TTL = 1 params.TTL = 1
aesnonce := make([]byte, 12) aesnonce := make([]byte, 12)
salt := make([]byte, 12) salt := make([]byte, 12)
randomize(aesnonce) mrand.Read(aesnonce)
randomize(salt) mrand.Read(salt)
env := NewEnvelope(params.TTL, params.Topic, salt, aesnonce, msg) env := NewEnvelope(params.TTL, params.Topic, salt, aesnonce, msg)
if err != nil { if err != nil {

View File

@ -18,6 +18,7 @@ package whisperv5
import ( import (
"bytes" "bytes"
mrand "math/rand"
"testing" "testing"
"time" "time"
@ -49,7 +50,7 @@ func TestWhisperBasic(t *testing.T) {
} }
peerID := make([]byte, 64) peerID := make([]byte, 64)
randomize(peerID) mrand.Read(peerID)
peer, _ := w.getPeer(peerID) peer, _ := w.getPeer(peerID)
if peer != nil { if peer != nil {
t.Fatal("found peer for random key.") t.Fatal("found peer for random key.")
@ -212,7 +213,7 @@ func TestWhisperSymKeyManagement(t *testing.T) {
// add existing id, nothing should change // add existing id, nothing should change
randomKey := make([]byte, 16) randomKey := make([]byte, 16)
randomize(randomKey) mrand.Read(randomKey)
err = w.AddSymKey(id1, randomKey) err = w.AddSymKey(id1, randomKey)
if err == nil { if err == nil {
t.Fatalf("failed AddSymKey with seed %d.", seed) t.Fatalf("failed AddSymKey with seed %d.", seed)