From c4ed55d80160a2b4f15cf01fc99cf17847ff8b01 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Thu, 22 Oct 2015 17:39:06 -0700 Subject: [PATCH] Refactor to move common libraries out of project --- .../github.com/codegangsta/cli/app_test.go | 2 +- .../github.com/codegangsta/cli/cli_test.go | 2 +- .../codegangsta/cli/command_test.go | 2 +- .../codegangsta/cli/context_test.go | 2 +- .../github.com/codegangsta/cli/flag_test.go | 2 +- .../github.com/codegangsta/cli/help_test.go | 2 +- .../websocket/examples/autobahn/server.go | 2 +- .../gorilla/websocket/examples/chat/conn.go | 2 +- .../websocket/examples/filewatch/main.go | 2 +- .../inconshreveable/log15/stack/stack_test.go | 2 +- .../go-stringutil/strings_bench_test.go | 2 +- .../naoina/go-stringutil/strings_test.go | 2 +- .../src/github.com/naoina/toml/decode.go | 2 +- .../naoina/toml/decode_bench_test.go | 2 +- .../src/github.com/naoina/toml/decode_test.go | 2 +- .../src/github.com/naoina/toml/encode.go | 2 +- .../src/github.com/naoina/toml/encode_test.go | 2 +- .../src/github.com/naoina/toml/parse.go | 2 +- .../github.com/spf13/pflag/example_test.go | 2 +- .../syndtr/goleveldb/leveldb/batch.go | 4 +- .../syndtr/goleveldb/leveldb/batch_test.go | 4 +- .../syndtr/goleveldb/leveldb/bench_test.go | 6 +- .../syndtr/goleveldb/leveldb/cache/cache.go | 2 +- .../syndtr/goleveldb/leveldb/comparer.go | 2 +- .../syndtr/goleveldb/leveldb/corrupt_test.go | 6 +- .../github.com/syndtr/goleveldb/leveldb/db.go | 16 +- .../syndtr/goleveldb/leveldb/db_compaction.go | 6 +- .../syndtr/goleveldb/leveldb/db_iter.go | 6 +- .../syndtr/goleveldb/leveldb/db_snapshot.go | 6 +- .../syndtr/goleveldb/leveldb/db_state.go | 4 +- .../syndtr/goleveldb/leveldb/db_test.go | 14 +- .../syndtr/goleveldb/leveldb/db_util.go | 10 +- .../syndtr/goleveldb/leveldb/db_write.go | 6 +- .../syndtr/goleveldb/leveldb/errors.go | 2 +- .../syndtr/goleveldb/leveldb/errors/errors.go | 4 +- .../syndtr/goleveldb/leveldb/external_test.go | 4 +- .../syndtr/goleveldb/leveldb/filter.go | 2 +- .../syndtr/goleveldb/leveldb/filter/bloom.go | 2 +- .../goleveldb/leveldb/filter/bloom_test.go | 2 +- .../goleveldb/leveldb/iterator/array_iter.go | 2 +- .../leveldb/iterator/array_iter_test.go | 4 +- .../leveldb/iterator/indexed_iter.go | 4 +- .../leveldb/iterator/indexed_iter_test.go | 6 +- .../syndtr/goleveldb/leveldb/iterator/iter.go | 2 +- .../leveldb/iterator/iter_suite_test.go | 2 +- .../goleveldb/leveldb/iterator/merged_iter.go | 6 +- .../leveldb/iterator/merged_iter_test.go | 6 +- .../goleveldb/leveldb/journal/journal.go | 4 +- .../syndtr/goleveldb/leveldb/key.go | 2 +- .../syndtr/goleveldb/leveldb/key_test.go | 2 +- .../goleveldb/leveldb/leveldb_suite_test.go | 2 +- .../goleveldb/leveldb/memdb/bench_test.go | 2 +- .../syndtr/goleveldb/leveldb/memdb/memdb.go | 8 +- .../leveldb/memdb/memdb_suite_test.go | 2 +- .../goleveldb/leveldb/memdb/memdb_test.go | 8 +- .../syndtr/goleveldb/leveldb/opt/options.go | 6 +- .../syndtr/goleveldb/leveldb/options.go | 4 +- .../syndtr/goleveldb/leveldb/session.go | 12 +- .../goleveldb/leveldb/session_record.go | 2 +- .../goleveldb/leveldb/session_record_test.go | 2 +- .../syndtr/goleveldb/leveldb/session_util.go | 4 +- .../goleveldb/leveldb/storage/file_storage.go | 2 +- .../goleveldb/leveldb/storage/mem_storage.go | 2 +- .../goleveldb/leveldb/storage/storage.go | 2 +- .../syndtr/goleveldb/leveldb/storage_test.go | 4 +- .../syndtr/goleveldb/leveldb/table.go | 12 +- .../goleveldb/leveldb/table/block_test.go | 8 +- .../syndtr/goleveldb/leveldb/table/reader.go | 18 +- .../leveldb/table/table_suite_test.go | 2 +- .../goleveldb/leveldb/table/table_test.go | 8 +- .../syndtr/goleveldb/leveldb/table/writer.go | 10 +- .../syndtr/goleveldb/leveldb/testutil/db.go | 6 +- .../syndtr/goleveldb/leveldb/testutil/iter.go | 2 +- .../syndtr/goleveldb/leveldb/testutil/kv.go | 2 +- .../goleveldb/leveldb/testutil/kvtest.go | 4 +- .../goleveldb/leveldb/testutil/storage.go | 4 +- .../syndtr/goleveldb/leveldb/testutil/util.go | 2 +- .../syndtr/goleveldb/leveldb/testutil_test.go | 8 +- .../syndtr/goleveldb/leveldb/util.go | 2 +- .../syndtr/goleveldb/leveldb/version.go | 6 +- .../github.com/tendermint/ed25519/ed25519.go | 2 +- .../ed25519/extra25519/extra25519.go | 2 +- .../github.com/tendermint/log15/handler.go | 2 +- .../src/github.com/tendermint/log15/root.go | 4 +- .../tendermint/log15/stack/stack_test.go | 2 +- .../src/golang.org/x/crypto/nacl/box/box.go | 6 +- .../golang.org/x/crypto/nacl/box/box_test.go | 2 +- .../x/crypto/nacl/secretbox/secretbox.go | 4 +- INSTALL/README.md | 2 +- account/account.go | 6 +- account/priv_account.go | 7 +- account/priv_key.go | 8 +- account/pub_key.go | 11 +- account/signature.go | 4 +- account/signature_test.go | 7 +- alert/alert.go | 2 +- alert/config.go | 3 +- alert/log.go | 2 +- blockchain/log.go | 2 +- blockchain/pool.go | 4 +- blockchain/pool_test.go | 3 +- blockchain/reactor.go | 6 +- blockchain/store.go | 7 +- cmd/barak/barak.go | 5 +- cmd/barak/log.go | 2 +- cmd/barak/main.go | 6 +- cmd/barak/types/command.go | 3 +- cmd/debora/commands.go | 4 +- cmd/debora/log.go | 2 +- cmd/debora/main.go | 9 +- cmd/logjack/main.go | 2 +- cmd/sim_txs/main.go | 3 +- cmd/stdinwriter/main.go | 2 +- cmd/tendermint/config.go | 2 +- cmd/tendermint/flags.go | 5 +- cmd/tendermint/gen_account.go | 5 +- cmd/tendermint/gen_validator.go | 2 +- cmd/tendermint/get_account.go | 2 +- cmd/tendermint/log.go | 2 +- cmd/tendermint/main.go | 4 +- cmd/tendermint/probe_upnp.go | 2 +- cmd/tendermint/send_tx.go | 2 +- cmd/tendermint/show_validator.go | 3 +- common/array.go | 5 - common/async.go | 15 - common/bit_array.go | 275 ----- common/bit_array_test.go | 120 --- common/byteslice.go | 44 - common/cmap.go | 62 -- common/colors.go | 84 -- common/errors.go | 45 - common/heap.go | 103 -- common/int.go | 55 - common/io.go | 75 -- common/math.go | 157 --- common/os.go | 225 ----- common/random.go | 145 --- common/repeat_timer.go | 72 -- common/service.go | 154 --- common/string.go | 24 - common/test/assert.go | 14 - common/test/mutate.go | 28 - common/throttle_timer.go | 57 -- common/word.go | 91 -- config/config.go | 5 +- config/log.go | 9 - config/tendermint/config.go | 4 +- config/tendermint_test/config.go | 5 +- consensus/config.go | 2 +- consensus/height_vote_set.go | 2 +- consensus/log.go | 2 +- consensus/reactor.go | 7 +- consensus/state.go | 4 +- consensus/state_test.go | 1 + consensus/test.go | 4 +- crawler/crawl.go | 2 +- crawler/log.go | 2 +- db/config.go | 13 - db/db.go | 50 - db/level_db.go | 82 -- db/mem_db.go | 44 - events/events.go | 2 +- events/log.go | 2 +- logger/config.go | 14 - logger/log.go | 55 - mempool/config.go | 3 +- mempool/log.go | 2 +- mempool/reactor.go | 6 +- merkle/README.md | 18 - merkle/iavl_node.go | 459 --------- merkle/iavl_proof.go | 151 --- merkle/iavl_test.go | 335 ------ merkle/iavl_tree.go | 262 ----- merkle/simple_tree.go | 298 ------ merkle/simple_tree_test.go | 119 --- merkle/types.go | 21 - merkle/util.go | 43 - node/config.go | 3 +- node/log.go | 2 +- node/node.go | 8 +- node/node_test.go | 2 +- p2p/README.md | 77 -- p2p/addrbook.go | 813 --------------- p2p/addrbook_test.go | 161 --- p2p/config.go | 13 - p2p/connection.go | 640 ------------ p2p/listener.go | 212 ---- p2p/log.go | 7 - p2p/netaddress.go | 217 ---- p2p/peer.go | 134 --- p2p/peer_set.go | 227 ----- p2p/peer_set_test.go | 169 ---- p2p/pex_reactor.go | 262 ----- p2p/secret_connection.go | 346 ------- p2p/secret_connection_test.go | 202 ---- p2p/switch.go | 391 ------- p2p/switch_test.go | 236 ----- p2p/upnp/README.md | 5 - p2p/upnp/log.go | 7 - p2p/upnp/probe.go | 111 -- p2p/upnp/upnp.go | 380 ------- p2p/util.go | 15 - p2p/version.go | 3 - permission/types/permissions.go | 2 +- permission/types/snatives.go | 2 +- rpc/client/client.go | 4 +- rpc/client/log.go | 3 +- rpc/core/accounts.go | 2 +- rpc/core/blocks.go | 2 +- rpc/core/config.go | 2 +- rpc/core/consensus.go | 2 +- rpc/core/log.go | 2 +- rpc/core/net.go | 2 +- rpc/core/pipe.go | 2 +- rpc/core/txs.go | 2 +- rpc/core/types/responses.go | 2 +- rpc/core_client/client.go | 2 +- rpc/core_client/log.go | 3 +- rpc/core_client/ws_client.go | 6 +- rpc/server/handlers.go | 7 +- rpc/server/http_server.go | 4 +- rpc/server/log.go | 2 +- rpc/test/config.go | 2 +- rpc/test/helpers.go | 4 +- rpc/test/tests.go | 2 +- rpc/test/ws_helpers.go | 4 +- scripts/unsafe_upgrade_group.sh | 9 + state/block_cache.go | 8 +- state/common.go | 2 +- state/execution.go | 2 +- state/genesis_test.go | 2 +- state/log.go | 2 +- state/permissions_test.go | 4 +- state/state.go | 9 +- state/tx_cache.go | 2 +- state/tx_cache_test.go | 2 +- state/types/genesis.go | 4 +- types/block.go | 6 +- types/config.go | 2 +- types/events.go | 4 +- types/log.go | 2 +- types/part_set.go | 8 +- types/part_set_test.go | 2 +- types/priv_validator.go | 7 +- types/proposal.go | 4 +- types/proposal_test.go | 2 +- types/tx.go | 6 +- types/tx_test.go | 2 +- types/validator.go | 4 +- types/validator_set.go | 4 +- types/validator_set_test.go | 2 +- types/vote.go | 4 +- types/vote_set.go | 4 +- types/vote_set_test.go | 4 +- vm/log.go | 2 +- vm/native.go | 5 +- vm/opcodes.go | 2 +- vm/snative.go | 2 +- vm/stack.go | 2 +- vm/test/fake_app_state.go | 2 +- vm/test/log_event_test.go | 2 +- vm/test/vm_test.go | 2 +- vm/types.go | 2 +- vm/vm.go | 2 +- wire/README.md | 138 --- wire/byteslice.go | 68 -- wire/codec.go | 171 ---- wire/int.go | 270 ----- wire/int_test.go | 79 -- wire/log.go | 18 - wire/reflect.go | 954 ------------------ wire/reflect_test.go | 508 ---------- wire/string.go | 33 - wire/time.go | 27 - wire/util.go | 78 -- wire/version.go | 3 - wire/wire.go | 134 --- 277 files changed, 406 insertions(+), 11304 deletions(-) delete mode 100644 common/array.go delete mode 100644 common/async.go delete mode 100644 common/bit_array.go delete mode 100644 common/bit_array_test.go delete mode 100644 common/byteslice.go delete mode 100644 common/cmap.go delete mode 100644 common/colors.go delete mode 100644 common/errors.go delete mode 100644 common/heap.go delete mode 100644 common/int.go delete mode 100644 common/io.go delete mode 100644 common/math.go delete mode 100644 common/os.go delete mode 100644 common/random.go delete mode 100644 common/repeat_timer.go delete mode 100644 common/service.go delete mode 100644 common/string.go delete mode 100644 common/test/assert.go delete mode 100644 common/test/mutate.go delete mode 100644 common/throttle_timer.go delete mode 100644 common/word.go delete mode 100644 config/log.go delete mode 100644 db/config.go delete mode 100644 db/db.go delete mode 100644 db/level_db.go delete mode 100644 db/mem_db.go delete mode 100644 logger/config.go delete mode 100644 logger/log.go delete mode 100644 merkle/README.md delete mode 100644 merkle/iavl_node.go delete mode 100644 merkle/iavl_proof.go delete mode 100644 merkle/iavl_test.go delete mode 100644 merkle/iavl_tree.go delete mode 100644 merkle/simple_tree.go delete mode 100644 merkle/simple_tree_test.go delete mode 100644 merkle/types.go delete mode 100644 merkle/util.go delete mode 100644 p2p/README.md delete mode 100644 p2p/addrbook.go delete mode 100644 p2p/addrbook_test.go delete mode 100644 p2p/config.go delete mode 100644 p2p/connection.go delete mode 100644 p2p/listener.go delete mode 100644 p2p/log.go delete mode 100644 p2p/netaddress.go delete mode 100644 p2p/peer.go delete mode 100644 p2p/peer_set.go delete mode 100644 p2p/peer_set_test.go delete mode 100644 p2p/pex_reactor.go delete mode 100644 p2p/secret_connection.go delete mode 100644 p2p/secret_connection_test.go delete mode 100644 p2p/switch.go delete mode 100644 p2p/switch_test.go delete mode 100644 p2p/upnp/README.md delete mode 100644 p2p/upnp/log.go delete mode 100644 p2p/upnp/probe.go delete mode 100644 p2p/upnp/upnp.go delete mode 100644 p2p/util.go delete mode 100644 p2p/version.go create mode 100755 scripts/unsafe_upgrade_group.sh delete mode 100644 wire/README.md delete mode 100644 wire/byteslice.go delete mode 100644 wire/codec.go delete mode 100644 wire/int.go delete mode 100644 wire/int_test.go delete mode 100644 wire/log.go delete mode 100644 wire/reflect.go delete mode 100644 wire/reflect_test.go delete mode 100644 wire/string.go delete mode 100644 wire/time.go delete mode 100644 wire/util.go delete mode 100644 wire/version.go delete mode 100644 wire/wire.go diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/app_test.go b/Godeps/_workspace/src/github.com/codegangsta/cli/app_test.go index 55e9e85c..ae8bb0f9 100644 --- a/Godeps/_workspace/src/github.com/codegangsta/cli/app_test.go +++ b/Godeps/_workspace/src/github.com/codegangsta/cli/app_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli" + "github.com/codegangsta/cli" ) func ExampleApp() { diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/cli_test.go b/Godeps/_workspace/src/github.com/codegangsta/cli/cli_test.go index 0583e95e..8a8df973 100644 --- a/Godeps/_workspace/src/github.com/codegangsta/cli/cli_test.go +++ b/Godeps/_workspace/src/github.com/codegangsta/cli/cli_test.go @@ -3,7 +3,7 @@ package cli_test import ( "os" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli" + "github.com/codegangsta/cli" ) func Example() { diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/command_test.go b/Godeps/_workspace/src/github.com/codegangsta/cli/command_test.go index e6bbefa2..4125b0c1 100644 --- a/Godeps/_workspace/src/github.com/codegangsta/cli/command_test.go +++ b/Godeps/_workspace/src/github.com/codegangsta/cli/command_test.go @@ -4,7 +4,7 @@ import ( "flag" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli" + "github.com/codegangsta/cli" ) func TestCommandDoNotIgnoreFlags(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/context_test.go b/Godeps/_workspace/src/github.com/codegangsta/cli/context_test.go index 166ab7da..d4a1877f 100644 --- a/Godeps/_workspace/src/github.com/codegangsta/cli/context_test.go +++ b/Godeps/_workspace/src/github.com/codegangsta/cli/context_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli" + "github.com/codegangsta/cli" ) func TestNewContext(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/flag_test.go b/Godeps/_workspace/src/github.com/codegangsta/cli/flag_test.go index a938c180..f0f096a2 100644 --- a/Godeps/_workspace/src/github.com/codegangsta/cli/flag_test.go +++ b/Godeps/_workspace/src/github.com/codegangsta/cli/flag_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli" + "github.com/codegangsta/cli" ) var boolFlagTests = []struct { diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/help_test.go b/Godeps/_workspace/src/github.com/codegangsta/cli/help_test.go index 5d0b5a3e..b3c1fda6 100644 --- a/Godeps/_workspace/src/github.com/codegangsta/cli/help_test.go +++ b/Godeps/_workspace/src/github.com/codegangsta/cli/help_test.go @@ -4,7 +4,7 @@ import ( "bytes" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli" + "github.com/codegangsta/cli" ) func Test_ShowAppHelp_NoAuthor(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go index 5315f840..d96ac84d 100644 --- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go +++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go @@ -8,7 +8,7 @@ package main import ( "errors" "flag" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/gorilla/websocket" + "github.com/gorilla/websocket" "io" "log" "net/http" diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go index ae66d976..7cc0496c 100644 --- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go +++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go @@ -5,7 +5,7 @@ package main import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/gorilla/websocket" + "github.com/gorilla/websocket" "log" "net/http" "time" diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go index 01a56b4f..a2c7b85f 100644 --- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go +++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go @@ -14,7 +14,7 @@ import ( "text/template" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/gorilla/websocket" + "github.com/gorilla/websocket" ) const ( diff --git a/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go b/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go index f16bdba9..52371b1e 100644 --- a/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go +++ b/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go @@ -9,7 +9,7 @@ import ( "runtime" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/inconshreveable/log15/stack" + "github.com/inconshreveable/log15/stack" ) type testType struct{} diff --git a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go index ed30f385..90c280bd 100644 --- a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go +++ b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go @@ -3,7 +3,7 @@ package stringutil_test import ( "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/go-stringutil" + "github.com/naoina/go-stringutil" ) var benchcaseForCamelCase = "the_quick_brown_fox_jumps_over_the_lazy_dog" diff --git a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go index 1070bff5..69c831e1 100644 --- a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go +++ b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/go-stringutil" + "github.com/naoina/go-stringutil" ) func TestToUpperCamelCase(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/naoina/toml/decode.go b/Godeps/_workspace/src/github.com/naoina/toml/decode.go index 28215cd8..3b2465c1 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/decode.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/decode.go @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/toml/ast" + "github.com/naoina/toml/ast" ) const ( diff --git a/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go b/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go index 385cdcc6..b85c1c68 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" ) func BenchmarkUnmarshal(b *testing.B) { diff --git a/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go b/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go index ca3fcc9b..1fcae9b7 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" ) const ( diff --git a/Godeps/_workspace/src/github.com/naoina/toml/encode.go b/Godeps/_workspace/src/github.com/naoina/toml/encode.go index 1e947a30..e50d5941 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/encode.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/encode.go @@ -8,7 +8,7 @@ import ( "go/ast" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/go-stringutil" + "github.com/naoina/go-stringutil" ) const ( diff --git a/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go b/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go index 32a606eb..17e04fd0 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" ) func TestMarshal(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/naoina/toml/parse.go b/Godeps/_workspace/src/github.com/naoina/toml/parse.go index f8a5498e..e0186662 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/parse.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/parse.go @@ -3,7 +3,7 @@ package toml import ( "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/toml/ast" + "github.com/naoina/toml/ast" ) // Parse returns an AST representation of TOML. diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go index 4b45f784..9be7a49f 100644 --- a/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go +++ b/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go @@ -11,7 +11,7 @@ import ( "strings" "time" - flag "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/spf13/pflag" + flag "github.com/spf13/pflag" ) // Example 1: A single string flag called "species" with default value "gopher". diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go index bff214f7..ccf390c9 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go @@ -10,8 +10,8 @@ import ( "encoding/binary" "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/memdb" ) type ErrBatchCorrupted struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go index 0510bb37..7fc842f4 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go @@ -10,8 +10,8 @@ import ( "bytes" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/memdb" ) type tbRec struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go index dc92ed93..91b42670 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go @@ -15,9 +15,9 @@ import ( "runtime" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" ) func randomString(r *rand.Rand, n int) []byte { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go index 0579b5f7..c9670de5 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go @@ -12,7 +12,7 @@ import ( "sync/atomic" "unsafe" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) // Cacher provides interface to implements a caching functionality. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go index 09a6d078..d33d5e9c 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go @@ -6,7 +6,7 @@ package leveldb -import "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" +import "github.com/syndtr/goleveldb/leveldb/comparer" type iComparer struct { ucmp comparer.Comparer diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go index 3482f03e..a351874e 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go @@ -9,9 +9,9 @@ package leveldb import ( "bytes" "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" "io" "math/rand" "testing" diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go index 88aa23c3..9da4eba0 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go @@ -17,14 +17,14 @@ import ( "sync/atomic" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/table" + "github.com/syndtr/goleveldb/leveldb/util" ) type DB struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go index eeefb347..447407ab 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go @@ -10,9 +10,9 @@ import ( "sync" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/opt" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go index 84afe9de..4607e5da 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go @@ -12,9 +12,9 @@ import ( "sync" "sync/atomic" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go index fe7c9745..0372848f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go @@ -13,9 +13,9 @@ import ( "sync" "sync/atomic" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) type snapshotElement struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go index a8805fa9..24ecab50 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go @@ -10,8 +10,8 @@ import ( "sync/atomic" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/memdb" ) type memDB struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go index e50f50f3..0acb567a 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go @@ -23,13 +23,13 @@ import ( "time" "unsafe" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) func tkey(i int) []byte { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go index 642d3630..a8a2bdf7 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go @@ -7,11 +7,11 @@ package leveldb import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) // Reader is the interface that wraps basic Get and NewIterator methods. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go index ea90d85a..e1cf30c5 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go @@ -9,9 +9,9 @@ package leveldb import ( "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) func (db *DB) writeJournal(b *Batch) error { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go index 7bc991b6..29d0d2f2 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go @@ -7,7 +7,7 @@ package leveldb import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/errors" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go index 573e1555..84b5d6b7 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go @@ -11,8 +11,8 @@ import ( "errors" "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go index 8fda3e35..b328ece4 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go @@ -10,8 +10,8 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/testutil" ) var _ = testutil.Defer(func() { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go index ba498855..37c1e146 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go @@ -7,7 +7,7 @@ package leveldb import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/filter" ) type iFilter struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go index 9f7cf124..bab0e997 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go @@ -7,7 +7,7 @@ package filter import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) func bloomHash(key []byte) uint32 { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go index 4d304a50..1fb56f07 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go @@ -8,7 +8,7 @@ package filter import ( "encoding/binary" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" "testing" ) diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go index 1aa77a5e..a23ab05f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go @@ -7,7 +7,7 @@ package iterator import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) // BasicArray is the interface that wraps basic Len and Search method. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go index 9bc91595..1ed6d07c 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go @@ -9,8 +9,8 @@ package iterator_test import ( . "github.com/onsi/ginkgo" - . "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + . "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" ) var _ = testutil.Defer(func() { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go index 133eb2be..939adbb9 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go @@ -7,8 +7,8 @@ package iterator import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) // IteratorIndexer is the interface that wraps CommonIterator and basic Get diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go index 1b55e563..72a79789 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go @@ -11,9 +11,9 @@ import ( . "github.com/onsi/ginkgo" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - . "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/comparer" + . "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" ) type keyValue struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go index 424f149c..c2522860 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go @@ -11,7 +11,7 @@ package iterator import ( "errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go index 431cc79f..5ef8d5ba 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go @@ -3,7 +3,7 @@ package iterator_test import ( "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestIterator(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go index 66d49335..1a7e29df 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go @@ -7,9 +7,9 @@ package iterator import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) type dir int diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go index 22700892..e523b63e 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go @@ -10,9 +10,9 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - . "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/comparer" + . "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" ) var _ = testutil.Defer(func() { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go index 1bd5eab3..6519ec66 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go @@ -82,8 +82,8 @@ import ( "fmt" "io" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) // These constants are part of the wire format and should not be changed. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go index f4ba09ae..572ae815 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go @@ -10,7 +10,7 @@ import ( "encoding/binary" "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/errors" ) type ErrIkeyCorrupted struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go index 0a4e8815..30eadf78 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go @@ -10,7 +10,7 @@ import ( "bytes" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/comparer" ) var defaultIComparer = &iComparer{comparer.DefaultComparer} diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go index 9103ab11..fefa007a 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go @@ -3,7 +3,7 @@ package leveldb import ( "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestLevelDB(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go index 6189357d..b05084ca 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go @@ -11,7 +11,7 @@ import ( "math/rand" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/comparer" ) func BenchmarkPut(b *testing.B) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go index dfda8dd2..e5398873 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go @@ -11,10 +11,10 @@ import ( "math/rand" "sync" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go index 61b1c97d..18c304b7 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go @@ -3,7 +3,7 @@ package memdb import ( "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestMemDB(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go index 5348a4a8..5dd6dbc7 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go @@ -10,10 +10,10 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) func (p *DB) TestFindLT(key []byte) (rkey, value []byte, err error) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go index 409659f1..86828f47 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go @@ -8,9 +8,9 @@ package opt import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/cache" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/filter" "math" ) diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go index 28f7eefe..a3d84ef6 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go @@ -7,8 +7,8 @@ package leveldb import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/opt" ) func dupOptions(o *opt.Options) *opt.Options { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go index 26ed3f62..b3906f7f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go @@ -13,12 +13,12 @@ import ( "sync" "sync/atomic" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) type ErrManifestCorrupted struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go index 4f03dbca..1bdcc68f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go @@ -12,7 +12,7 @@ import ( "io" "strings" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/errors" ) type byteReader interface { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go index 6550ded1..c0c035ae 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go @@ -10,7 +10,7 @@ import ( "bytes" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/opt" ) func decodeEncode(v *sessionRecord) (res bool, err error) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go index 8d44f777..007c02cd 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go @@ -10,8 +10,8 @@ import ( "fmt" "sync/atomic" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/storage" ) // Logging. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go index 882ad7eb..46cc9d07 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go @@ -18,7 +18,7 @@ import ( "sync" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) var errFileOpen = errors.New("leveldb/storage: file still open") diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go index 6c4084c1..fc1c8165 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go @@ -11,7 +11,7 @@ import ( "os" "sync" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) const typeShift = 3 diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go index e62ab098..85dd70b0 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go @@ -12,7 +12,7 @@ import ( "fmt" "io" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) type FileType uint32 diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go index 17fb0277..dc1f1fb5 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go @@ -17,8 +17,8 @@ import ( "sync" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) const typeShift = 4 diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go index 2d10945b..066b4dac 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go @@ -11,12 +11,12 @@ import ( "sort" "sync/atomic" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/cache" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/table" + "github.com/syndtr/goleveldb/leveldb/util" ) type // tFile holds basic information about a table. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go index 6d28d74e..00e6f9ee 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go @@ -13,10 +13,10 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) type blockTesting struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go index f5e762c2..6976cb74 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go @@ -14,15 +14,15 @@ import ( "strings" "sync" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy" + "github.com/syndtr/goleveldb/leveldb/cache" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/gosnappy/snappy" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go index 64c902d8..6465da6e 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go @@ -3,7 +3,7 @@ package table import ( "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestTable(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go index cb1f2e0a..4b59b31f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go @@ -12,10 +12,10 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) type tableWrapper struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go index e8690ade..cfabb1a1 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go @@ -12,11 +12,11 @@ import ( "fmt" "io" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/gosnappy/snappy" ) func sharedPrefixLen(a, b []byte) int { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go index 47ecdc7b..ec3f177a 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go @@ -12,9 +12,9 @@ import ( . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/util" ) type DB interface{} diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go index 8e8d947f..df6d9db6 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go @@ -12,7 +12,7 @@ import ( . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/iterator" ) type IterAct int diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go index dcd53fe5..471d5708 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go @@ -12,7 +12,7 @@ import ( "sort" "strings" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) type KeyValueEntry struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go index 2f4989a7..a0b58f0e 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go @@ -13,8 +13,8 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) func KeyValueTesting(rnd *rand.Rand, kv KeyValue, p DB, setup func(KeyValue) DB, teardown func(DB)) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go index 4bfc70a0..59c496d5 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go @@ -18,8 +18,8 @@ import ( . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go index 8b0a5bf3..97c5294b 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go @@ -15,7 +15,7 @@ import ( "github.com/onsi/ginkgo/config" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/comparer" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go index ced5b930..25bf2b29 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go @@ -9,10 +9,10 @@ package leveldb import ( . "github.com/onsi/gomega" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) type testingDB struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go index fe9c8459..1a5bf71a 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go @@ -10,7 +10,7 @@ import ( "fmt" "sort" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/storage" ) func shorten(str string) string { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go index f7557d24..5ab7b53d 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go @@ -10,9 +10,9 @@ import ( "sync/atomic" "unsafe" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) type tSet struct { diff --git a/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go b/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go index 41c6f227..48ac4a42 100644 --- a/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go +++ b/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go @@ -14,7 +14,7 @@ import ( "crypto/subtle" "io" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/agl/ed25519/edwards25519" + "github.com/agl/ed25519/edwards25519" ) const ( diff --git a/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go b/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go index 11a70e65..571218f5 100644 --- a/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go +++ b/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go @@ -7,7 +7,7 @@ package extra25519 import ( "crypto/sha512" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/agl/ed25519/edwards25519" + "github.com/agl/ed25519/edwards25519" ) // PrivateKeyToCurve25519 converts an ed25519 private key into a corresponding diff --git a/Godeps/_workspace/src/github.com/tendermint/log15/handler.go b/Godeps/_workspace/src/github.com/tendermint/log15/handler.go index 2ca3dbcb..4c771b4b 100644 --- a/Godeps/_workspace/src/github.com/tendermint/log15/handler.go +++ b/Godeps/_workspace/src/github.com/tendermint/log15/handler.go @@ -11,7 +11,7 @@ import ( "sync/atomic" "unsafe" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/inconshreveable/log15/stack" + "github.com/inconshreveable/log15/stack" ) // A Logger prints its log records by writing to a Handler. diff --git a/Godeps/_workspace/src/github.com/tendermint/log15/root.go b/Godeps/_workspace/src/github.com/tendermint/log15/root.go index fc3c2308..98103173 100644 --- a/Godeps/_workspace/src/github.com/tendermint/log15/root.go +++ b/Godeps/_workspace/src/github.com/tendermint/log15/root.go @@ -3,8 +3,8 @@ package log15 import ( "os" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/inconshreveable/log15/term" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/mattn/go-colorable" + "github.com/inconshreveable/log15/term" + "github.com/mattn/go-colorable" ) var ( diff --git a/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go b/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go index f16bdba9..52371b1e 100644 --- a/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go @@ -9,7 +9,7 @@ import ( "runtime" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/inconshreveable/log15/stack" + "github.com/inconshreveable/log15/stack" ) type testType struct{} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box.go b/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box.go index a940f516..ffe00baf 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box.go @@ -18,9 +18,9 @@ This package is interoperable with NaCl: http://nacl.cr.yp.to/box.html. package box import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/curve25519" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/nacl/secretbox" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/salsa20/salsa" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/nacl/secretbox" + "golang.org/x/crypto/salsa20/salsa" "io" ) diff --git a/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box_test.go b/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box_test.go index 5d48f3b0..481ade28 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box_test.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/nacl/box/box_test.go @@ -10,7 +10,7 @@ import ( "encoding/hex" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/curve25519" + "golang.org/x/crypto/curve25519" ) func TestSealOpen(t *testing.T) { diff --git a/Godeps/_workspace/src/golang.org/x/crypto/nacl/secretbox/secretbox.go b/Godeps/_workspace/src/golang.org/x/crypto/nacl/secretbox/secretbox.go index fc4a6f5b..ed46ba2f 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/nacl/secretbox/secretbox.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/nacl/secretbox/secretbox.go @@ -18,8 +18,8 @@ This package is interoperable with NaCl: http://nacl.cr.yp.to/secretbox.html. package secretbox import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/poly1305" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/salsa20/salsa" + "golang.org/x/crypto/poly1305" + "golang.org/x/crypto/salsa20/salsa" ) // Overhead is the number of bytes of overhead when boxing a message. diff --git a/INSTALL/README.md b/INSTALL/README.md index 751d346c..ba888e1f 100644 --- a/INSTALL/README.md +++ b/INSTALL/README.md @@ -26,5 +26,5 @@ WARNING: THIS STEP WILL GIVE CONTROL OF THE CURRENT USER TO THE DEV TEAM. go get -u github.com/tendermint/tendermint/cmd/tendermint mkdir -p ~/.tendermint - cp $GOPATH/src/github.com/tendermint/tendermint/config/tendermint/genesis.json ~/.tendermint/ + cp $GOPATH/src/github.com/tendermint/go-config/tendermint/genesis.json ~/.tendermint/ tendermint node --seeds="goldenalchemist.chaintest.net:46656" diff --git a/account/account.go b/account/account.go index 97af5e05..cb1983d7 100644 --- a/account/account.go +++ b/account/account.go @@ -5,9 +5,9 @@ import ( "fmt" "io" - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/merkle" + "github.com/tendermint/go-wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-merkle" ptypes "github.com/tendermint/tendermint/permission/types" ) diff --git a/account/priv_account.go b/account/priv_account.go index d299e076..b46493fb 100644 --- a/account/priv_account.go +++ b/account/priv_account.go @@ -1,9 +1,10 @@ + package account import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/ed25519" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) type PrivAccount struct { diff --git a/account/priv_key.go b/account/priv_key.go index 87b65821..78d39272 100644 --- a/account/priv_key.go +++ b/account/priv_key.go @@ -1,10 +1,10 @@ package account import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519" - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" + "github.com/tendermint/ed25519" + "github.com/tendermint/ed25519/extra25519" + "github.com/tendermint/go-wire" + . "github.com/tendermint/go-common" ) // PrivKey is part of PrivAccount and state.PrivValidator. diff --git a/account/pub_key.go b/account/pub_key.go index c83c1e2b..0e7d8fa0 100644 --- a/account/pub_key.go +++ b/account/pub_key.go @@ -1,13 +1,14 @@ + package account import ( "bytes" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/ripemd160" - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" + "github.com/tendermint/ed25519" + "github.com/tendermint/ed25519/extra25519" + "golang.org/x/crypto/ripemd160" + "github.com/tendermint/go-wire" + . "github.com/tendermint/go-common" ) // PubKey is part of Account and Validator. diff --git a/account/signature.go b/account/signature.go index fbf3cdda..1224c5c9 100644 --- a/account/signature.go +++ b/account/signature.go @@ -3,8 +3,8 @@ package account import ( "fmt" - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" + "github.com/tendermint/go-wire" + . "github.com/tendermint/go-common" ) // Signature is a part of Txs and consensus Votes. diff --git a/account/signature_test.go b/account/signature_test.go index b9d45658..09d35b91 100644 --- a/account/signature_test.go +++ b/account/signature_test.go @@ -1,12 +1,13 @@ + package account import ( "bytes" "testing" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519" - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" + "github.com/tendermint/ed25519" + "github.com/tendermint/go-wire" + . "github.com/tendermint/go-common" ) func TestSignAndValidate(t *testing.T) { diff --git a/alert/alert.go b/alert/alert.go index b0e03ff2..c4763309 100644 --- a/alert/alert.go +++ b/alert/alert.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/sfreiberg/gotwilio" + "github.com/sfreiberg/gotwilio" ) var lastAlertUnix int64 = 0 diff --git a/alert/config.go b/alert/config.go index 834803fa..4a7bf771 100644 --- a/alert/config.go +++ b/alert/config.go @@ -1,7 +1,8 @@ + package alert import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/alert/log.go b/alert/log.go index 0f0740e0..58055cf2 100644 --- a/alert/log.go +++ b/alert/log.go @@ -1,7 +1,7 @@ package alert import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "alert") diff --git a/blockchain/log.go b/blockchain/log.go index f04e9994..29dc03f6 100644 --- a/blockchain/log.go +++ b/blockchain/log.go @@ -1,7 +1,7 @@ package blockchain import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "blockchain") diff --git a/blockchain/pool.go b/blockchain/pool.go index b7293b88..77428eae 100644 --- a/blockchain/pool.go +++ b/blockchain/pool.go @@ -5,8 +5,8 @@ import ( "sync" "time" - flow "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol" - . "github.com/tendermint/tendermint/common" + flow "github.com/tendermint/flowcontrol" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/types" ) diff --git a/blockchain/pool_test.go b/blockchain/pool_test.go index a70c96d5..c91f3368 100644 --- a/blockchain/pool_test.go +++ b/blockchain/pool_test.go @@ -1,3 +1,4 @@ + package blockchain import ( @@ -5,7 +6,7 @@ import ( "testing" "time" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/types" ) diff --git a/blockchain/reactor.go b/blockchain/reactor.go index 23e3ad2a..1f2a9eb8 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -7,12 +7,12 @@ import ( "reflect" "time" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) const ( diff --git a/blockchain/store.go b/blockchain/store.go index e4488a3f..7f08c581 100644 --- a/blockchain/store.go +++ b/blockchain/store.go @@ -1,3 +1,4 @@ + package blockchain import ( @@ -6,9 +7,9 @@ import ( "fmt" "io" - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" - dbm "github.com/tendermint/tendermint/db" + "github.com/tendermint/go-wire" + . "github.com/tendermint/go-common" + dbm "github.com/tendermint/go-db" "github.com/tendermint/tendermint/types" ) diff --git a/cmd/barak/barak.go b/cmd/barak/barak.go index 8cffee1f..2105b506 100644 --- a/cmd/barak/barak.go +++ b/cmd/barak/barak.go @@ -1,3 +1,4 @@ + package main import ( @@ -10,9 +11,9 @@ import ( "sync" "time" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" . "github.com/tendermint/tendermint/cmd/barak/types" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" pcm "github.com/tendermint/tendermint/process" "github.com/tendermint/tendermint/rpc/server" ) diff --git a/cmd/barak/log.go b/cmd/barak/log.go index c0472378..ce626d2e 100644 --- a/cmd/barak/log.go +++ b/cmd/barak/log.go @@ -1,7 +1,7 @@ package main import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "main") diff --git a/cmd/barak/main.go b/cmd/barak/main.go index 8c54fddf..0f244547 100644 --- a/cmd/barak/main.go +++ b/cmd/barak/main.go @@ -17,11 +17,11 @@ import ( "time" . "github.com/tendermint/tendermint/cmd/barak/types" - . "github.com/tendermint/tendermint/common" - cfg "github.com/tendermint/tendermint/config" + . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" pcm "github.com/tendermint/tendermint/process" "github.com/tendermint/tendermint/rpc/server" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) const BarakVersion = "0.0.1" diff --git a/cmd/barak/types/command.go b/cmd/barak/types/command.go index a393273d..e94de62d 100644 --- a/cmd/barak/types/command.go +++ b/cmd/barak/types/command.go @@ -1,8 +1,9 @@ + package types import ( acm "github.com/tendermint/tendermint/account" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) type AuthCommand struct { diff --git a/cmd/debora/commands.go b/cmd/debora/commands.go index 84487c2a..793f54e1 100644 --- a/cmd/debora/commands.go +++ b/cmd/debora/commands.go @@ -7,9 +7,9 @@ import ( "os" acm "github.com/tendermint/tendermint/account" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" btypes "github.com/tendermint/tendermint/cmd/barak/types" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/rpc/client" "net/http" ) diff --git a/cmd/debora/log.go b/cmd/debora/log.go index c0472378..ce626d2e 100644 --- a/cmd/debora/log.go +++ b/cmd/debora/log.go @@ -1,7 +1,7 @@ package main import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "main") diff --git a/cmd/debora/main.go b/cmd/debora/main.go index 402ea520..b4b836fc 100644 --- a/cmd/debora/main.go +++ b/cmd/debora/main.go @@ -1,8 +1,9 @@ + package main import ( "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/codegangsta/cli" + "github.com/codegangsta/cli" "io/ioutil" "net/url" "os" @@ -12,9 +13,9 @@ import ( acm "github.com/tendermint/tendermint/account" btypes "github.com/tendermint/tendermint/cmd/barak/types" - . "github.com/tendermint/tendermint/common" - cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" + "github.com/tendermint/go-wire" ) func remoteNick(remote string) string { diff --git a/cmd/logjack/main.go b/cmd/logjack/main.go index f73ac506..4a636a4a 100644 --- a/cmd/logjack/main.go +++ b/cmd/logjack/main.go @@ -10,7 +10,7 @@ import ( "strings" "time" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ) const Version = "0.0.1" diff --git a/cmd/sim_txs/main.go b/cmd/sim_txs/main.go index 70a67449..10462d41 100644 --- a/cmd/sim_txs/main.go +++ b/cmd/sim_txs/main.go @@ -1,3 +1,4 @@ + package main import ( @@ -6,7 +7,7 @@ import ( "fmt" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" cclient "github.com/tendermint/tendermint/rpc/core_client" diff --git a/cmd/stdinwriter/main.go b/cmd/stdinwriter/main.go index 87c75d45..b9eba402 100644 --- a/cmd/stdinwriter/main.go +++ b/cmd/stdinwriter/main.go @@ -6,7 +6,7 @@ import ( "io" "os" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ) const Version = "0.0.1" diff --git a/cmd/tendermint/config.go b/cmd/tendermint/config.go index a9c9b5da..ae47f4c2 100644 --- a/cmd/tendermint/config.go +++ b/cmd/tendermint/config.go @@ -1,7 +1,7 @@ package main import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/cmd/tendermint/flags.go b/cmd/tendermint/flags.go index ff402c33..b9ab7ff9 100644 --- a/cmd/tendermint/flags.go +++ b/cmd/tendermint/flags.go @@ -1,10 +1,11 @@ + package main import ( - flag "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/spf13/pflag" + flag "github.com/spf13/pflag" "os" - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) func parseFlags(config cfg.Config, args []string) { diff --git a/cmd/tendermint/gen_account.go b/cmd/tendermint/gen_account.go index 9a6ad6b1..d2dffc52 100644 --- a/cmd/tendermint/gen_account.go +++ b/cmd/tendermint/gen_account.go @@ -1,11 +1,12 @@ + package main import ( "fmt" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) func gen_account() { diff --git a/cmd/tendermint/gen_validator.go b/cmd/tendermint/gen_validator.go index e0e58e34..344d61bf 100644 --- a/cmd/tendermint/gen_validator.go +++ b/cmd/tendermint/gen_validator.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func gen_validator() { diff --git a/cmd/tendermint/get_account.go b/cmd/tendermint/get_account.go index 384be1b9..d2452d16 100644 --- a/cmd/tendermint/get_account.go +++ b/cmd/tendermint/get_account.go @@ -4,7 +4,7 @@ import ( "encoding/hex" "fmt" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" cclient "github.com/tendermint/tendermint/rpc/core_client" ) diff --git a/cmd/tendermint/log.go b/cmd/tendermint/log.go index c0472378..ce626d2e 100644 --- a/cmd/tendermint/log.go +++ b/cmd/tendermint/log.go @@ -1,7 +1,7 @@ package main import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "main") diff --git a/cmd/tendermint/main.go b/cmd/tendermint/main.go index eb9157bf..a266399a 100644 --- a/cmd/tendermint/main.go +++ b/cmd/tendermint/main.go @@ -4,8 +4,8 @@ import ( "fmt" "os" - . "github.com/tendermint/tendermint/common" - cfg "github.com/tendermint/tendermint/config" + . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" tmcfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tendermint/node" ) diff --git a/cmd/tendermint/probe_upnp.go b/cmd/tendermint/probe_upnp.go index 927e2548..5dcadddc 100644 --- a/cmd/tendermint/probe_upnp.go +++ b/cmd/tendermint/probe_upnp.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - "github.com/tendermint/tendermint/p2p/upnp" + "github.com/tendermint/go-p2p/upnp" ) func probe_upnp() { diff --git a/cmd/tendermint/send_tx.go b/cmd/tendermint/send_tx.go index 3da39801..2144826c 100644 --- a/cmd/tendermint/send_tx.go +++ b/cmd/tendermint/send_tx.go @@ -6,7 +6,7 @@ import ( "strconv" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" cclient "github.com/tendermint/tendermint/rpc/core_client" "github.com/tendermint/tendermint/types" ) diff --git a/cmd/tendermint/show_validator.go b/cmd/tendermint/show_validator.go index 0c743f71..52082b00 100644 --- a/cmd/tendermint/show_validator.go +++ b/cmd/tendermint/show_validator.go @@ -1,10 +1,11 @@ + package main import ( "fmt" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func show_validator() { diff --git a/common/array.go b/common/array.go deleted file mode 100644 index adedc42b..00000000 --- a/common/array.go +++ /dev/null @@ -1,5 +0,0 @@ -package common - -func Arr(items ...interface{}) []interface{} { - return items -} diff --git a/common/async.go b/common/async.go deleted file mode 100644 index 1d302c34..00000000 --- a/common/async.go +++ /dev/null @@ -1,15 +0,0 @@ -package common - -import "sync" - -func Parallel(tasks ...func()) { - var wg sync.WaitGroup - wg.Add(len(tasks)) - for _, task := range tasks { - go func(task func()) { - task() - wg.Done() - }(task) - } - wg.Wait() -} diff --git a/common/bit_array.go b/common/bit_array.go deleted file mode 100644 index dc006f0e..00000000 --- a/common/bit_array.go +++ /dev/null @@ -1,275 +0,0 @@ -package common - -import ( - "fmt" - "math/rand" - "strings" - "sync" -) - -type BitArray struct { - mtx sync.Mutex - Bits int `json:"bits"` // NOTE: persisted via reflect, must be exported - Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported -} - -// There is no BitArray whose Size is 0. Use nil instead. -func NewBitArray(bits int) *BitArray { - if bits == 0 { - return nil - } - return &BitArray{ - Bits: bits, - Elems: make([]uint64, (bits+63)/64), - } -} - -func (bA *BitArray) Size() int { - if bA == nil { - return 0 - } - return bA.Bits -} - -// NOTE: behavior is undefined if i >= bA.Bits -func (bA *BitArray) GetIndex(i int) bool { - if bA == nil { - return false - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - return bA.getIndex(i) -} - -func (bA *BitArray) getIndex(i int) bool { - if i >= bA.Bits { - return false - } - return bA.Elems[i/64]&(uint64(1)< 0 -} - -// NOTE: behavior is undefined if i >= bA.Bits -func (bA *BitArray) SetIndex(i int, v bool) bool { - if bA == nil { - return false - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - return bA.setIndex(i, v) -} - -func (bA *BitArray) setIndex(i int, v bool) bool { - if i >= bA.Bits { - return false - } - if v { - bA.Elems[i/64] |= (uint64(1) << uint(i%64)) - } else { - bA.Elems[i/64] &= ^(uint64(1) << uint(i%64)) - } - return true -} - -func (bA *BitArray) Copy() *BitArray { - if bA == nil { - return nil - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - return bA.copy() -} - -func (bA *BitArray) copy() *BitArray { - c := make([]uint64, len(bA.Elems)) - copy(c, bA.Elems) - return &BitArray{ - Bits: bA.Bits, - Elems: c, - } -} - -func (bA *BitArray) copyBits(bits int) *BitArray { - c := make([]uint64, (bits+63)/64) - copy(c, bA.Elems) - return &BitArray{ - Bits: bits, - Elems: c, - } -} - -// Returns a BitArray of larger bits size. -func (bA *BitArray) Or(o *BitArray) *BitArray { - if bA == nil { - o.Copy() - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - c := bA.copyBits(MaxInt(bA.Bits, o.Bits)) - for i := 0; i < len(c.Elems); i++ { - c.Elems[i] |= o.Elems[i] - } - return c -} - -// Returns a BitArray of smaller bit size. -func (bA *BitArray) And(o *BitArray) *BitArray { - if bA == nil { - return nil - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - return bA.and(o) -} - -func (bA *BitArray) and(o *BitArray) *BitArray { - c := bA.copyBits(MinInt(bA.Bits, o.Bits)) - for i := 0; i < len(c.Elems); i++ { - c.Elems[i] &= o.Elems[i] - } - return c -} - -func (bA *BitArray) Not() *BitArray { - if bA == nil { - return nil // Degenerate - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - c := bA.copy() - for i := 0; i < len(c.Elems); i++ { - c.Elems[i] = ^c.Elems[i] - } - return c -} - -func (bA *BitArray) Sub(o *BitArray) *BitArray { - if bA == nil { - return nil - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - if bA.Bits > o.Bits { - c := bA.copy() - for i := 0; i < len(o.Elems)-1; i++ { - c.Elems[i] &= ^c.Elems[i] - } - i := len(o.Elems) - 1 - if i >= 0 { - for idx := i * 64; idx < o.Bits; idx++ { - // NOTE: each individual GetIndex() call to o is safe. - c.setIndex(idx, c.getIndex(idx) && !o.GetIndex(idx)) - } - } - return c - } else { - return bA.and(o.Not()) // Note degenerate case where o == nil - } -} - -func (bA *BitArray) IsFull() bool { - if bA == nil { - return true - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - - // Check all elements except the last - for _, elem := range bA.Elems[:len(bA.Elems)-1] { - if (^elem) != 0 { - return false - } - } - - // Check that the last element has (lastElemBits) 1's - lastElemBits := (bA.Bits+63)%64 + 1 - lastElem := bA.Elems[len(bA.Elems)-1] - return (lastElem+1)&((uint64(1)< 0 { - randBitStart := rand.Intn(64) - for j := 0; j < 64; j++ { - bitIdx := ((j + randBitStart) % 64) - if (bA.Elems[elemIdx] & (uint64(1) << uint(bitIdx))) > 0 { - return 64*elemIdx + bitIdx, true - } - } - PanicSanity("should not happen") - } - } else { - // Special case for last elem, to ignore straggler bits - elemBits := bA.Bits % 64 - if elemBits == 0 { - elemBits = 64 - } - randBitStart := rand.Intn(elemBits) - for j := 0; j < elemBits; j++ { - bitIdx := ((j + randBitStart) % elemBits) - if (bA.Elems[elemIdx] & (uint64(1) << uint(bitIdx))) > 0 { - return 64*elemIdx + bitIdx, true - } - } - } - } - return 0, false -} - -func (bA *BitArray) String() string { - if bA == nil { - return "nil-BitArray" - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - return bA.stringIndented("") -} - -func (bA *BitArray) StringIndented(indent string) string { - if bA == nil { - return "nil-BitArray" - } - bA.mtx.Lock() - defer bA.mtx.Unlock() - return bA.stringIndented(indent) -} - -func (bA *BitArray) stringIndented(indent string) string { - - lines := []string{} - bits := "" - for i := 0; i < bA.Bits; i++ { - if bA.getIndex(i) { - bits += "X" - } else { - bits += "_" - } - if i%100 == 99 { - lines = append(lines, bits) - bits = "" - } - if i%10 == 9 { - bits += " " - } - if i%50 == 49 { - bits += " " - } - } - if len(bits) > 0 { - lines = append(lines, bits) - } - return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent)) -} diff --git a/common/bit_array_test.go b/common/bit_array_test.go deleted file mode 100644 index 93274aab..00000000 --- a/common/bit_array_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package common - -import ( - "testing" -) - -func randBitArray(bits int) (*BitArray, []byte) { - src := RandBytes((bits + 7) / 8) - bA := NewBitArray(bits) - for i := 0; i < len(src); i++ { - for j := 0; j < 8; j++ { - if i*8+j >= bits { - return bA, src - } - setBit := src[i]&(1< 0 - bA.SetIndex(i*8+j, setBit) - } - } - return bA, src -} - -func TestAnd(t *testing.T) { - - bA1, _ := randBitArray(51) - bA2, _ := randBitArray(31) - bA3 := bA1.And(bA2) - - if bA3.Bits != 31 { - t.Error("Expected min bits", bA3.Bits) - } - if len(bA3.Elems) != len(bA2.Elems) { - t.Error("Expected min elems length") - } - for i := 0; i < bA3.Bits; i++ { - expected := bA1.GetIndex(i) && bA2.GetIndex(i) - if bA3.GetIndex(i) != expected { - t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i)) - } - } -} - -func TestOr(t *testing.T) { - - bA1, _ := randBitArray(51) - bA2, _ := randBitArray(31) - bA3 := bA1.Or(bA2) - - if bA3.Bits != 51 { - t.Error("Expected max bits") - } - if len(bA3.Elems) != len(bA1.Elems) { - t.Error("Expected max elems length") - } - for i := 0; i < bA3.Bits; i++ { - expected := bA1.GetIndex(i) || bA2.GetIndex(i) - if bA3.GetIndex(i) != expected { - t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i)) - } - } -} - -func TestSub1(t *testing.T) { - - bA1, _ := randBitArray(31) - bA2, _ := randBitArray(51) - bA3 := bA1.Sub(bA2) - - if bA3.Bits != bA1.Bits { - t.Error("Expected bA1 bits") - } - if len(bA3.Elems) != len(bA1.Elems) { - t.Error("Expected bA1 elems length") - } - for i := 0; i < bA3.Bits; i++ { - expected := bA1.GetIndex(i) - if bA2.GetIndex(i) { - expected = false - } - if bA3.GetIndex(i) != expected { - t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i)) - } - } -} - -func TestSub2(t *testing.T) { - - bA1, _ := randBitArray(51) - bA2, _ := randBitArray(31) - bA3 := bA1.Sub(bA2) - - if bA3.Bits != bA1.Bits { - t.Error("Expected bA1 bits") - } - if len(bA3.Elems) != len(bA1.Elems) { - t.Error("Expected bA1 elems length") - } - for i := 0; i < bA3.Bits; i++ { - expected := bA1.GetIndex(i) - if i < bA2.Bits && bA2.GetIndex(i) { - expected = false - } - if bA3.GetIndex(i) != expected { - t.Error("Wrong bit from bA3") - } - } -} - -func TestPickRandom(t *testing.T) { - for idx := 0; idx < 123; idx++ { - bA1 := NewBitArray(123) - bA1.SetIndex(idx, true) - index, ok := bA1.PickRandom() - if !ok { - t.Fatal("Expected to pick element but got none") - } - if index != idx { - t.Fatalf("Expected to pick element at %v but got wrong index", idx) - } - } -} diff --git a/common/byteslice.go b/common/byteslice.go deleted file mode 100644 index be828f06..00000000 --- a/common/byteslice.go +++ /dev/null @@ -1,44 +0,0 @@ -package common - -import ( - "bytes" -) - -func Fingerprint(slice []byte) []byte { - fingerprint := make([]byte, 6) - copy(fingerprint, slice) - return fingerprint -} - -func IsZeros(slice []byte) bool { - for _, byt := range slice { - if byt != byte(0) { - return false - } - } - return true -} - -func RightPadBytes(slice []byte, l int) []byte { - if l < len(slice) { - return slice - } - padded := make([]byte, l) - copy(padded[0:len(slice)], slice) - return padded -} - -func LeftPadBytes(slice []byte, l int) []byte { - if l < len(slice) { - return slice - } - padded := make([]byte, l) - copy(padded[l-len(slice):], slice) - return padded -} - -func TrimmedString(b []byte) string { - trimSet := string([]byte{0}) - return string(bytes.TrimLeft(b, trimSet)) - -} diff --git a/common/cmap.go b/common/cmap.go deleted file mode 100644 index 5de6fa2f..00000000 --- a/common/cmap.go +++ /dev/null @@ -1,62 +0,0 @@ -package common - -import "sync" - -// CMap is a goroutine-safe map -type CMap struct { - m map[string]interface{} - l sync.Mutex -} - -func NewCMap() *CMap { - return &CMap{ - m: make(map[string]interface{}, 0), - } -} - -func (cm *CMap) Set(key string, value interface{}) { - cm.l.Lock() - defer cm.l.Unlock() - cm.m[key] = value -} - -func (cm *CMap) Get(key string) interface{} { - cm.l.Lock() - defer cm.l.Unlock() - return cm.m[key] -} - -func (cm *CMap) Has(key string) bool { - cm.l.Lock() - defer cm.l.Unlock() - _, ok := cm.m[key] - return ok -} - -func (cm *CMap) Delete(key string) { - cm.l.Lock() - defer cm.l.Unlock() - delete(cm.m, key) -} - -func (cm *CMap) Size() int { - cm.l.Lock() - defer cm.l.Unlock() - return len(cm.m) -} - -func (cm *CMap) Clear() { - cm.l.Lock() - defer cm.l.Unlock() - cm.m = make(map[string]interface{}, 0) -} - -func (cm *CMap) Values() []interface{} { - cm.l.Lock() - defer cm.l.Unlock() - items := []interface{}{} - for _, v := range cm.m { - items = append(items, v) - } - return items -} diff --git a/common/colors.go b/common/colors.go deleted file mode 100644 index 776b22e2..00000000 --- a/common/colors.go +++ /dev/null @@ -1,84 +0,0 @@ -package common - -import ( - "fmt" - "strings" -) - -const ( - ANSIReset = "\x1b[0m" - ANSIBright = "\x1b[1m" - ANSIDim = "\x1b[2m" - ANSIUnderscore = "\x1b[4m" - ANSIBlink = "\x1b[5m" - ANSIReverse = "\x1b[7m" - ANSIHidden = "\x1b[8m" - - ANSIFgBlack = "\x1b[30m" - ANSIFgRed = "\x1b[31m" - ANSIFgGreen = "\x1b[32m" - ANSIFgYellow = "\x1b[33m" - ANSIFgBlue = "\x1b[34m" - ANSIFgMagenta = "\x1b[35m" - ANSIFgCyan = "\x1b[36m" - ANSIFgWhite = "\x1b[37m" - - ANSIBgBlack = "\x1b[40m" - ANSIBgRed = "\x1b[41m" - ANSIBgGreen = "\x1b[42m" - ANSIBgYellow = "\x1b[43m" - ANSIBgBlue = "\x1b[44m" - ANSIBgMagenta = "\x1b[45m" - ANSIBgCyan = "\x1b[46m" - ANSIBgWhite = "\x1b[47m" -) - -// color the string s with color 'color' -// unless s is already colored -func treat(s string, color string) string { - if len(s) > 2 && s[:2] == "\x1b[" { - return s - } else { - return color + s + ANSIReset - } -} - -func treatAll(color string, args ...interface{}) string { - var parts []string - for _, arg := range args { - parts = append(parts, treat(fmt.Sprintf("%v", arg), color)) - } - return strings.Join(parts, "") -} - -func Black(args ...interface{}) string { - return treatAll(ANSIFgBlack, args...) -} - -func Red(args ...interface{}) string { - return treatAll(ANSIFgRed, args...) -} - -func Green(args ...interface{}) string { - return treatAll(ANSIFgGreen, args...) -} - -func Yellow(args ...interface{}) string { - return treatAll(ANSIFgYellow, args...) -} - -func Blue(args ...interface{}) string { - return treatAll(ANSIFgBlue, args...) -} - -func Magenta(args ...interface{}) string { - return treatAll(ANSIFgMagenta, args...) -} - -func Cyan(args ...interface{}) string { - return treatAll(ANSIFgCyan, args...) -} - -func White(args ...interface{}) string { - return treatAll(ANSIFgWhite, args...) -} diff --git a/common/errors.go b/common/errors.go deleted file mode 100644 index e168a75b..00000000 --- a/common/errors.go +++ /dev/null @@ -1,45 +0,0 @@ -package common - -import ( - "fmt" -) - -type StackError struct { - Err interface{} - Stack []byte -} - -func (se StackError) String() string { - return fmt.Sprintf("Error: %v\nStack: %s", se.Err, se.Stack) -} - -func (se StackError) Error() string { - return se.String() -} - -//-------------------------------------------------------------------------------------------------- -// panic wrappers - -// A panic resulting from a sanity check means there is a programmer error -// and some gaurantee is not satisfied. -func PanicSanity(v interface{}) { - panic(Fmt("Paniced on a Sanity Check: %v", v)) -} - -// A panic here means something has gone horribly wrong, in the form of data corruption or -// failure of the operating system. In a correct/healthy system, these should never fire. -// If they do, it's indicative of a much more serious problem. -func PanicCrisis(v interface{}) { - panic(Fmt("Paniced on a Crisis: %v", v)) -} - -// Indicates a failure of consensus. Someone was malicious or something has -// gone horribly wrong. These should really boot us into an "emergency-recover" mode -func PanicConsensus(v interface{}) { - panic(Fmt("Paniced on a Consensus Failure: %v", v)) -} - -// For those times when we're not sure if we should panic -func PanicQ(v interface{}) { - panic(Fmt("Paniced questionably: %v", v)) -} diff --git a/common/heap.go b/common/heap.go deleted file mode 100644 index 4a96d7aa..00000000 --- a/common/heap.go +++ /dev/null @@ -1,103 +0,0 @@ -package common - -import ( - "container/heap" -) - -type Comparable interface { - Less(o interface{}) bool -} - -//----------------------------------------------------------------------------- - -/* -Example usage: - h := NewHeap() - - h.Push(String("msg1"), 1) - h.Push(String("msg3"), 3) - h.Push(String("msg2"), 2) - - fmt.Println(h.Pop()) - fmt.Println(h.Pop()) - fmt.Println(h.Pop()) -*/ - -type Heap struct { - pq priorityQueue -} - -func NewHeap() *Heap { - return &Heap{pq: make([]*pqItem, 0)} -} - -func (h *Heap) Len() int64 { - return int64(len(h.pq)) -} - -func (h *Heap) Push(value interface{}, priority Comparable) { - heap.Push(&h.pq, &pqItem{value: value, priority: priority}) -} - -func (h *Heap) Peek() interface{} { - if len(h.pq) == 0 { - return nil - } - return h.pq[0].value -} - -func (h *Heap) Update(value interface{}, priority Comparable) { - h.pq.Update(h.pq[0], value, priority) -} - -func (h *Heap) Pop() interface{} { - item := heap.Pop(&h.pq).(*pqItem) - return item.value -} - -//----------------------------------------------------------------------------- - -/////////////////////// -// From: http://golang.org/pkg/container/heap/#example__priorityQueue - -type pqItem struct { - value interface{} - priority Comparable - index int -} - -type priorityQueue []*pqItem - -func (pq priorityQueue) Len() int { return len(pq) } - -func (pq priorityQueue) Less(i, j int) bool { - return pq[i].priority.Less(pq[j].priority) -} - -func (pq priorityQueue) Swap(i, j int) { - pq[i], pq[j] = pq[j], pq[i] - pq[i].index = i - pq[j].index = j -} - -func (pq *priorityQueue) Push(x interface{}) { - n := len(*pq) - item := x.(*pqItem) - item.index = n - *pq = append(*pq, item) -} - -func (pq *priorityQueue) Pop() interface{} { - old := *pq - n := len(old) - item := old[n-1] - item.index = -1 // for safety - *pq = old[0 : n-1] - return item -} - -func (pq *priorityQueue) Update(item *pqItem, value interface{}, priority Comparable) { - item.value = value - item.priority = priority - heap.Fix(pq, item.index) -} diff --git a/common/int.go b/common/int.go deleted file mode 100644 index 50e86a07..00000000 --- a/common/int.go +++ /dev/null @@ -1,55 +0,0 @@ -package common - -import ( - "encoding/binary" - "sort" -) - -// Sort for []uint64 - -type Uint64Slice []uint64 - -func (p Uint64Slice) Len() int { return len(p) } -func (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] } -func (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p Uint64Slice) Sort() { sort.Sort(p) } - -func SearchUint64s(a []uint64, x uint64) int { - return sort.Search(len(a), func(i int) bool { return a[i] >= x }) -} - -func (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) } - -//----------------------------------------------------------------------------- - -func PutUint64LE(dest []byte, i uint64) { - binary.LittleEndian.PutUint64(dest, i) -} - -func GetUint64LE(src []byte) uint64 { - return binary.LittleEndian.Uint64(src) -} - -func PutUint64BE(dest []byte, i uint64) { - binary.BigEndian.PutUint64(dest, i) -} - -func GetUint64BE(src []byte) uint64 { - return binary.BigEndian.Uint64(src) -} - -func PutInt64LE(dest []byte, i int64) { - binary.LittleEndian.PutUint64(dest, uint64(i)) -} - -func GetInt64LE(src []byte) int64 { - return int64(binary.LittleEndian.Uint64(src)) -} - -func PutInt64BE(dest []byte, i int64) { - binary.BigEndian.PutUint64(dest, uint64(i)) -} - -func GetInt64BE(src []byte) int64 { - return int64(binary.BigEndian.Uint64(src)) -} diff --git a/common/io.go b/common/io.go deleted file mode 100644 index 378c19fc..00000000 --- a/common/io.go +++ /dev/null @@ -1,75 +0,0 @@ -package common - -import ( - "bytes" - "errors" - "io" -) - -type PrefixedReader struct { - Prefix []byte - reader io.Reader -} - -func NewPrefixedReader(prefix []byte, reader io.Reader) *PrefixedReader { - return &PrefixedReader{prefix, reader} -} - -func (pr *PrefixedReader) Read(p []byte) (n int, err error) { - if len(pr.Prefix) > 0 { - read := copy(p, pr.Prefix) - pr.Prefix = pr.Prefix[read:] - return read, nil - } else { - return pr.reader.Read(p) - } -} - -// NOTE: Not goroutine safe -type BufferCloser struct { - bytes.Buffer - Closed bool -} - -func NewBufferCloser(buf []byte) *BufferCloser { - return &BufferCloser{ - *bytes.NewBuffer(buf), - false, - } -} - -func (bc *BufferCloser) Close() error { - if bc.Closed { - return errors.New("BufferCloser already closed") - } - bc.Closed = true - return nil -} - -func (bc *BufferCloser) Write(p []byte) (n int, err error) { - if bc.Closed { - return 0, errors.New("Cannot write to closed BufferCloser") - } - return bc.Buffer.Write(p) -} - -func (bc *BufferCloser) WriteByte(c byte) error { - if bc.Closed { - return errors.New("Cannot write to closed BufferCloser") - } - return bc.Buffer.WriteByte(c) -} - -func (bc *BufferCloser) WriteRune(r rune) (n int, err error) { - if bc.Closed { - return 0, errors.New("Cannot write to closed BufferCloser") - } - return bc.Buffer.WriteRune(r) -} - -func (bc *BufferCloser) WriteString(s string) (n int, err error) { - if bc.Closed { - return 0, errors.New("Cannot write to closed BufferCloser") - } - return bc.Buffer.WriteString(s) -} diff --git a/common/math.go b/common/math.go deleted file mode 100644 index b037d1a7..00000000 --- a/common/math.go +++ /dev/null @@ -1,157 +0,0 @@ -package common - -func MaxInt8(a, b int8) int8 { - if a > b { - return a - } - return b -} - -func MaxUint8(a, b uint8) uint8 { - if a > b { - return a - } - return b -} - -func MaxInt16(a, b int16) int16 { - if a > b { - return a - } - return b -} - -func MaxUint16(a, b uint16) uint16 { - if a > b { - return a - } - return b -} - -func MaxInt32(a, b int32) int32 { - if a > b { - return a - } - return b -} - -func MaxUint32(a, b uint32) uint32 { - if a > b { - return a - } - return b -} - -func MaxInt64(a, b int64) int64 { - if a > b { - return a - } - return b -} - -func MaxUint64(a, b uint64) uint64 { - if a > b { - return a - } - return b -} - -func MaxInt(a, b int) int { - if a > b { - return a - } - return b -} - -func MaxUint(a, b uint) uint { - if a > b { - return a - } - return b -} - -//----------------------------------------------------------------------------- - -func MinInt8(a, b int8) int8 { - if a < b { - return a - } - return b -} - -func MinUint8(a, b uint8) uint8 { - if a < b { - return a - } - return b -} - -func MinInt16(a, b int16) int16 { - if a < b { - return a - } - return b -} - -func MinUint16(a, b uint16) uint16 { - if a < b { - return a - } - return b -} - -func MinInt32(a, b int32) int32 { - if a < b { - return a - } - return b -} - -func MinUint32(a, b uint32) uint32 { - if a < b { - return a - } - return b -} - -func MinInt64(a, b int64) int64 { - if a < b { - return a - } - return b -} - -func MinUint64(a, b uint64) uint64 { - if a < b { - return a - } - return b -} - -func MinInt(a, b int) int { - if a < b { - return a - } - return b -} - -func MinUint(a, b uint) uint { - if a < b { - return a - } - return b -} - -//----------------------------------------------------------------------------- - -func ExpUint64(a, b uint64) uint64 { - accum := uint64(1) - for b > 0 { - if b&1 == 1 { - accum *= a - } - a *= a - b >>= 1 - } - return accum -} diff --git a/common/os.go b/common/os.go deleted file mode 100644 index 170c6f82..00000000 --- a/common/os.go +++ /dev/null @@ -1,225 +0,0 @@ -package common - -import ( - "bufio" - "fmt" - "io/ioutil" - "os" - "os/signal" - "strings" - "sync" - "time" -) - -var ( - GoPath = os.Getenv("GOPATH") -) - -func TrapSignal(cb func()) { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt) - signal.Notify(c, os.Kill) - go func() { - for sig := range c { - fmt.Printf("captured %v, exiting...\n", sig) - if cb != nil { - cb() - } - os.Exit(1) - } - }() - select {} -} - -func Exit(s string) { - fmt.Printf(s + "\n") - os.Exit(1) -} - -func EnsureDir(dir string) error { - if _, err := os.Stat(dir); os.IsNotExist(err) { - err := os.MkdirAll(dir, 0700) - if err != nil { - return fmt.Errorf("Could not create directory %v. %v", dir, err) - } - } - return nil -} - -func FileExists(filePath string) bool { - _, err := os.Stat(filePath) - return !os.IsNotExist(err) -} - -func ReadFile(filePath string) ([]byte, error) { - return ioutil.ReadFile(filePath) -} - -func MustReadFile(filePath string) []byte { - fileBytes, err := ioutil.ReadFile(filePath) - if err != nil { - Exit(Fmt("MustReadFile failed: %v", err)) - return nil - } - return fileBytes -} - -func WriteFile(filePath string, contents []byte) error { - err := ioutil.WriteFile(filePath, contents, 0600) - if err != nil { - return err - } - // fmt.Printf("File written to %v.\n", filePath) - return nil -} - -func MustWriteFile(filePath string, contents []byte) { - err := WriteFile(filePath, contents) - if err != nil { - Exit(Fmt("MustWriteFile failed: %v", err)) - } -} - -// Writes to newBytes to filePath. -// Guaranteed not to lose *both* oldBytes and newBytes, -// (assuming that the OS is perfect) -func WriteFileAtomic(filePath string, newBytes []byte) error { - // If a file already exists there, copy to filePath+".bak" (overwrite anything) - if _, err := os.Stat(filePath); !os.IsNotExist(err) { - fileBytes, err := ioutil.ReadFile(filePath) - if err != nil { - return fmt.Errorf("Could not read file %v. %v", filePath, err) - } - err = ioutil.WriteFile(filePath+".bak", fileBytes, 0600) - if err != nil { - return fmt.Errorf("Could not write file %v. %v", filePath+".bak", err) - } - } - // Write newBytes to filePath.new - err := ioutil.WriteFile(filePath+".new", newBytes, 0600) - if err != nil { - return fmt.Errorf("Could not write file %v. %v", filePath+".new", err) - } - // Move filePath.new to filePath - err = os.Rename(filePath+".new", filePath) - return err -} - -//-------------------------------------------------------------------------------- - -/* AutoFile usage - -// Create/Append to ./autofile_test -af, err := OpenAutoFile("autofile_test") -if err != nil { - panic(err) -} - -// Stream of writes. -// During this time, the file may be moved e.g. by logRotate. -for i := 0; i < 60; i++ { - af.Write([]byte(Fmt("LOOP(%v)", i))) - time.Sleep(time.Second) -} - -// Close the AutoFile -err = af.Close() -if err != nil { - panic(err) -} -*/ - -const autoFileOpenDuration = 1000 * time.Millisecond - -// Automatically closes and re-opens file for writing. -// This is useful for using a log file with the logrotate tool. -type AutoFile struct { - Path string - ticker *time.Ticker - mtx sync.Mutex - file *os.File -} - -func OpenAutoFile(path string) (af *AutoFile, err error) { - af = &AutoFile{ - Path: path, - ticker: time.NewTicker(autoFileOpenDuration), - } - if err = af.openFile(); err != nil { - return - } - go af.processTicks() - return -} - -func (af *AutoFile) Close() error { - af.ticker.Stop() - af.mtx.Lock() - err := af.closeFile() - af.mtx.Unlock() - return err -} - -func (af *AutoFile) processTicks() { - for { - _, ok := <-af.ticker.C - if !ok { - return // Done. - } - af.mtx.Lock() - af.closeFile() - af.mtx.Unlock() - } -} - -func (af *AutoFile) closeFile() (err error) { - file := af.file - if file == nil { - return nil - } - af.file = nil - return file.Close() -} - -func (af *AutoFile) Write(b []byte) (n int, err error) { - af.mtx.Lock() - defer af.mtx.Unlock() - if af.file == nil { - if err = af.openFile(); err != nil { - return - } - } - return af.file.Write(b) -} - -func (af *AutoFile) openFile() error { - file, err := os.OpenFile(af.Path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600) - if err != nil { - return err - } - af.file = file - return nil -} - -func Tempfile(prefix string) (*os.File, string) { - file, err := ioutil.TempFile("", prefix) - if err != nil { - PanicCrisis(err) - } - return file, file.Name() -} - -func Prompt(prompt string, defaultValue string) (string, error) { - fmt.Print(prompt) - reader := bufio.NewReader(os.Stdin) - line, err := reader.ReadString('\n') - if err != nil { - return defaultValue, err - } else { - line = strings.TrimSpace(line) - if line == "" { - return defaultValue, nil - } - return line, nil - } -} diff --git a/common/random.go b/common/random.go deleted file mode 100644 index 64560115..00000000 --- a/common/random.go +++ /dev/null @@ -1,145 +0,0 @@ -package common - -import ( - crand "crypto/rand" - "encoding/hex" - "math/rand" - "time" -) - -const ( - strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters -) - -func init() { - // Seed math/rand with "secure" int64 - b := CRandBytes(8) - var seed uint64 - for i := 0; i < 8; i++ { - seed |= uint64(b[i]) - seed <<= 8 - } - rand.Seed(int64(seed)) -} - -// Constructs an alphanumeric string of given length. -func RandStr(length int) string { - chars := []byte{} -MAIN_LOOP: - for { - val := rand.Int63() - for i := 0; i < 10; i++ { - v := int(val & 0x3f) // rightmost 6 bits - if v >= 62 { // only 62 characters in strChars - val >>= 6 - continue - } else { - chars = append(chars, strChars[v]) - if len(chars) == length { - break MAIN_LOOP - } - val >>= 6 - } - } - } - - return string(chars) -} - -func RandUint16() uint16 { - return uint16(rand.Uint32() & (1<<16 - 1)) -} - -func RandUint32() uint32 { - return rand.Uint32() -} - -func RandUint64() uint64 { - return uint64(rand.Uint32())<<32 + uint64(rand.Uint32()) -} - -func RandUint() uint { - return uint(rand.Int()) -} - -func RandInt16() int16 { - return int16(rand.Uint32() & (1<<16 - 1)) -} - -func RandInt32() int32 { - return int32(rand.Uint32()) -} - -func RandInt64() int64 { - return int64(rand.Uint32())<<32 + int64(rand.Uint32()) -} - -func RandInt() int { - return rand.Int() -} - -// Distributed pseudo-exponentially to test for various cases -func RandUint16Exp() uint16 { - bits := rand.Uint32() % 16 - if bits == 0 { - return 0 - } - n := uint16(1 << (bits - 1)) - n += uint16(rand.Int31()) & ((1 << (bits - 1)) - 1) - return n -} - -// Distributed pseudo-exponentially to test for various cases -func RandUint32Exp() uint32 { - bits := rand.Uint32() % 32 - if bits == 0 { - return 0 - } - n := uint32(1 << (bits - 1)) - n += uint32(rand.Int31()) & ((1 << (bits - 1)) - 1) - return n -} - -// Distributed pseudo-exponentially to test for various cases -func RandUint64Exp() uint64 { - bits := rand.Uint32() % 64 - if bits == 0 { - return 0 - } - n := uint64(1 << (bits - 1)) - n += uint64(rand.Int63()) & ((1 << (bits - 1)) - 1) - return n -} - -func RandFloat32() float32 { - return rand.Float32() -} - -func RandTime() time.Time { - return time.Unix(int64(RandUint64Exp()), 0) -} - -func RandBytes(n int) []byte { - bs := make([]byte, n) - for i := 0; i < n; i++ { - bs[i] = byte(rand.Intn(256)) - } - return bs -} - -//----------------------------------------------------------------------------- -// CRand* methods are crypto safe. - -func CRandBytes(numBytes int) []byte { - b := make([]byte, numBytes) - _, err := crand.Read(b) - if err != nil { - PanicCrisis(err) - } - return b -} - -// RandHex(24) gives 96 bits of randomness, strong enough for most purposes. -func CRandHex(numDigits int) string { - return hex.EncodeToString(CRandBytes(numDigits / 2)) -} diff --git a/common/repeat_timer.go b/common/repeat_timer.go deleted file mode 100644 index e2aa18ea..00000000 --- a/common/repeat_timer.go +++ /dev/null @@ -1,72 +0,0 @@ -package common - -import "time" -import "sync" - -/* -RepeatTimer repeatedly sends a struct{}{} to .Ch after each "dur" period. -It's good for keeping connections alive. -A RepeatTimer must be Stop()'d or it will keep a goroutine alive. -*/ -type RepeatTimer struct { - Ch chan time.Time - - mtx sync.Mutex - name string - ticker *time.Ticker - quit chan struct{} - dur time.Duration -} - -func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer { - var t = &RepeatTimer{ - Ch: make(chan time.Time), - ticker: time.NewTicker(dur), - quit: make(chan struct{}), - name: name, - dur: dur, - } - go t.fireRoutine(t.ticker) - return t -} - -func (t *RepeatTimer) fireRoutine(ticker *time.Ticker) { - for { - select { - case t_ := <-ticker.C: - t.Ch <- t_ - case <-t.quit: - return - } - } -} - -// Wait the duration again before firing. -func (t *RepeatTimer) Reset() { - t.Stop() - - t.mtx.Lock() // Lock - defer t.mtx.Unlock() - - t.ticker = time.NewTicker(t.dur) - t.quit = make(chan struct{}) - go t.fireRoutine(t.ticker) -} - -// For ease of .Stop()'ing services before .Start()'ing them, -// we ignore .Stop()'s on nil RepeatTimers. -func (t *RepeatTimer) Stop() bool { - if t == nil { - return false - } - t.mtx.Lock() // Lock - defer t.mtx.Unlock() - - exists := t.ticker != nil - if exists { - t.ticker.Stop() - t.ticker = nil - close(t.quit) - } - return exists -} diff --git a/common/service.go b/common/service.go deleted file mode 100644 index 05b2aded..00000000 --- a/common/service.go +++ /dev/null @@ -1,154 +0,0 @@ -/* - -Classical-inheritance-style service declarations. -Services can be started, then stopped. -Users can override the OnStart/OnStop methods. -These methods are guaranteed to be called at most once. -Caller must ensure that Start() and Stop() are not called concurrently. -It is ok to call Stop() without calling Start() first. -Services cannot be re-started unless otherwise documented. - -Typical usage: - -type FooService struct { - BaseService - // private fields -} - -func NewFooService() *FooService { - fs := &FooService{ - // init - } - fs.BaseService = *NewBaseService(log, "FooService", fs) - return fs -} - -func (fs *FooService) OnStart() error { - fs.BaseService.OnStart() // Always call the overridden method. - // initialize private fields - // start subroutines, etc. -} - -func (fs *FooService) OnStop() error { - fs.BaseService.OnStop() // Always call the overridden method. - // close/destroy private fields - // stop subroutines, etc. -} - -*/ -package common - -import "sync/atomic" -import "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" - -type Service interface { - Start() (bool, error) - OnStart() error - - Stop() bool - OnStop() - - IsRunning() bool - - String() string -} - -type BaseService struct { - log log15.Logger - name string - started uint32 // atomic - stopped uint32 // atomic - - // The "subclass" of BaseService - impl Service -} - -func NewBaseService(log log15.Logger, name string, impl Service) *BaseService { - return &BaseService{ - log: log, - name: name, - impl: impl, - } -} - -// Implements Servce -func (bs *BaseService) Start() (bool, error) { - if atomic.CompareAndSwapUint32(&bs.started, 0, 1) { - if atomic.LoadUint32(&bs.stopped) == 1 { - if bs.log != nil { - bs.log.Warn(Fmt("Not starting %v -- already stopped", bs.name), "impl", bs.impl) - } - return false, nil - } else { - if bs.log != nil { - bs.log.Notice(Fmt("Starting %v", bs.name), "impl", bs.impl) - } - } - err := bs.impl.OnStart() - return true, err - } else { - if bs.log != nil { - bs.log.Info(Fmt("Not starting %v -- already started", bs.name), "impl", bs.impl) - } - return false, nil - } -} - -// Implements Service -func (bs *BaseService) OnStart() error { return nil } - -// Implements Service -func (bs *BaseService) Stop() bool { - if atomic.CompareAndSwapUint32(&bs.stopped, 0, 1) { - if bs.log != nil { - bs.log.Notice(Fmt("Stopping %v", bs.name), "impl", bs.impl) - } - bs.impl.OnStop() - return true - } else { - if bs.log != nil { - bs.log.Notice(Fmt("Not stopping %v", bs.name), "impl", bs.impl) - } - return false - } -} - -// Implements Service -func (bs *BaseService) OnStop() {} - -// Implements Service -func (bs *BaseService) IsRunning() bool { - return atomic.LoadUint32(&bs.started) == 1 && atomic.LoadUint32(&bs.stopped) == 0 -} - -// Implements Servce -func (bs *BaseService) String() string { - return bs.name -} - -//---------------------------------------- - -type QuitService struct { - BaseService - Quit chan struct{} -} - -func NewQuitService(log log15.Logger, name string, impl Service) *QuitService { - return &QuitService{ - BaseService: *NewBaseService(log, name, impl), - Quit: nil, - } -} - -// NOTE: when overriding OnStart, must call .QuitService.OnStart(). -func (qs *QuitService) OnStart() error { - qs.Quit = make(chan struct{}) - return nil -} - -// NOTE: when overriding OnStop, must call .QuitService.OnStop(). -func (qs *QuitService) OnStop() { - if qs.Quit != nil { - close(qs.Quit) - } -} diff --git a/common/string.go b/common/string.go deleted file mode 100644 index a4d221b7..00000000 --- a/common/string.go +++ /dev/null @@ -1,24 +0,0 @@ -package common - -import ( - "fmt" - "strings" -) - -var Fmt = fmt.Sprintf - -func RightPadString(s string, totalLength int) string { - remaining := totalLength - len(s) - if remaining > 0 { - s = s + strings.Repeat(" ", remaining) - } - return s -} - -func LeftPadString(s string, totalLength int) string { - remaining := totalLength - len(s) - if remaining > 0 { - s = strings.Repeat(" ", remaining) + s - } - return s -} diff --git a/common/test/assert.go b/common/test/assert.go deleted file mode 100644 index a6ffed0c..00000000 --- a/common/test/assert.go +++ /dev/null @@ -1,14 +0,0 @@ -package test - -import ( - "testing" -) - -func AssertPanics(t *testing.T, msg string, f func()) { - defer func() { - if err := recover(); err == nil { - t.Errorf("Should have panic'd, but didn't: %v", msg) - } - }() - f() -} diff --git a/common/test/mutate.go b/common/test/mutate.go deleted file mode 100644 index 39bf9055..00000000 --- a/common/test/mutate.go +++ /dev/null @@ -1,28 +0,0 @@ -package test - -import ( - . "github.com/tendermint/tendermint/common" -) - -// Contract: !bytes.Equal(input, output) && len(input) >= len(output) -func MutateByteSlice(bytez []byte) []byte { - // If bytez is empty, panic - if len(bytez) == 0 { - panic("Cannot mutate an empty bytez") - } - - // Copy bytez - mBytez := make([]byte, len(bytez)) - copy(mBytez, bytez) - bytez = mBytez - - // Try a random mutation - switch RandInt() % 2 { - case 0: // Mutate a single byte - bytez[RandInt()%len(bytez)] += byte(RandInt()%255 + 1) - case 1: // Remove an arbitrary byte - pos := RandInt() % len(bytez) - bytez = append(bytez[:pos], bytez[pos+1:]...) - } - return bytez -} diff --git a/common/throttle_timer.go b/common/throttle_timer.go deleted file mode 100644 index 0b40a60c..00000000 --- a/common/throttle_timer.go +++ /dev/null @@ -1,57 +0,0 @@ -package common - -import ( - "sync/atomic" - "time" -) - -/* -ThrottleTimer fires an event at most "dur" after each .Set() call. -If a short burst of .Set() calls happens, ThrottleTimer fires once. -If a long continuous burst of .Set() calls happens, ThrottleTimer fires -at most once every "dur". -*/ -type ThrottleTimer struct { - Name string - Ch chan struct{} - quit chan struct{} - dur time.Duration - timer *time.Timer - isSet uint32 -} - -func NewThrottleTimer(name string, dur time.Duration) *ThrottleTimer { - var ch = make(chan struct{}) - var quit = make(chan struct{}) - var t = &ThrottleTimer{Name: name, Ch: ch, dur: dur, quit: quit} - t.timer = time.AfterFunc(dur, t.fireRoutine) - t.timer.Stop() - return t -} - -func (t *ThrottleTimer) fireRoutine() { - select { - case t.Ch <- struct{}{}: - atomic.StoreUint32(&t.isSet, 0) - case <-t.quit: - // do nothing - default: - t.timer.Reset(t.dur) - } -} - -func (t *ThrottleTimer) Set() { - if atomic.CompareAndSwapUint32(&t.isSet, 0, 1) { - t.timer.Reset(t.dur) - } -} - -// For ease of .Stop()'ing services before .Start()'ing them, -// we ignore .Stop()'s on nil ThrottleTimers -func (t *ThrottleTimer) Stop() bool { - if t == nil { - return false - } - close(t.quit) - return t.timer.Stop() -} diff --git a/common/word.go b/common/word.go deleted file mode 100644 index 4072482b..00000000 --- a/common/word.go +++ /dev/null @@ -1,91 +0,0 @@ -package common - -import ( - "bytes" - "sort" -) - -var ( - Zero256 = Word256{0} - One256 = Word256{1} -) - -type Word256 [32]byte - -func (w Word256) String() string { return string(w[:]) } -func (w Word256) TrimmedString() string { return TrimmedString(w.Bytes()) } -func (w Word256) Copy() Word256 { return w } -func (w Word256) Bytes() []byte { return w[:] } // copied. -func (w Word256) Prefix(n int) []byte { return w[:n] } -func (w Word256) Postfix(n int) []byte { return w[32-n:] } -func (w Word256) IsZero() bool { - accum := byte(0) - for _, byt := range w { - accum |= byt - } - return accum == 0 -} -func (w Word256) Compare(other Word256) int { - return bytes.Compare(w[:], other[:]) -} - -func Uint64ToWord256(i uint64) Word256 { - buf := [8]byte{} - PutUint64BE(buf[:], i) - return LeftPadWord256(buf[:]) -} - -func Int64ToWord256(i int64) Word256 { - buf := [8]byte{} - PutInt64BE(buf[:], i) - return LeftPadWord256(buf[:]) -} - -func RightPadWord256(bz []byte) (word Word256) { - copy(word[:], bz) - return -} - -func LeftPadWord256(bz []byte) (word Word256) { - copy(word[32-len(bz):], bz) - return -} - -func Uint64FromWord256(word Word256) uint64 { - buf := word.Postfix(8) - return GetUint64BE(buf) -} - -func Int64FromWord256(word Word256) int64 { - buf := word.Postfix(8) - return GetInt64BE(buf) -} - -//------------------------------------- - -type Tuple256 struct { - First Word256 - Second Word256 -} - -func (tuple Tuple256) Compare(other Tuple256) int { - firstCompare := tuple.First.Compare(other.First) - if firstCompare == 0 { - return tuple.Second.Compare(other.Second) - } else { - return firstCompare - } -} - -func Tuple256Split(t Tuple256) (Word256, Word256) { - return t.First, t.Second -} - -type Tuple256Slice []Tuple256 - -func (p Tuple256Slice) Len() int { return len(p) } -func (p Tuple256Slice) Less(i, j int) bool { - return p[i].Compare(p[j]) < 0 -} -func (p Tuple256Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p Tuple256Slice) Sort() { sort.Sort(p) } diff --git a/config/config.go b/config/config.go index c9becc98..21c6b81f 100644 --- a/config/config.go +++ b/config/config.go @@ -1,11 +1,12 @@ + package config import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" "sync" "time" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ) type Config interface { diff --git a/config/log.go b/config/log.go deleted file mode 100644 index fb526d8b..00000000 --- a/config/log.go +++ /dev/null @@ -1,9 +0,0 @@ -package config - -import ( - // We can't use github.com/tendermint/tendermint/logger - // because that would create a dependency cycle. - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" -) - -var log = log15.New("module", "config") diff --git a/config/tendermint/config.go b/config/tendermint/config.go index e18f3c83..df37891a 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -5,8 +5,8 @@ import ( "path" "strings" - . "github.com/tendermint/tendermint/common" - cfg "github.com/tendermint/tendermint/config" + . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" ) func getTMRoot(rootDir string) string { diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index 9e530a71..1eec76b6 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -1,3 +1,4 @@ + // Import this in all *_test.go files to initialize ~/.tendermint_test. package tendermint_test @@ -7,8 +8,8 @@ import ( "path" "strings" - . "github.com/tendermint/tendermint/common" - cfg "github.com/tendermint/tendermint/config" + . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" ) func init() { diff --git a/consensus/config.go b/consensus/config.go index 8366b36c..a5c8e6fa 100644 --- a/consensus/config.go +++ b/consensus/config.go @@ -1,7 +1,7 @@ package consensus import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/consensus/height_vote_set.go b/consensus/height_vote_set.go index eb680cd6..aa87728b 100644 --- a/consensus/height_vote_set.go +++ b/consensus/height_vote_set.go @@ -4,7 +4,7 @@ import ( "strings" "sync" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/types" ) diff --git a/consensus/log.go b/consensus/log.go index 0b3a33db..0514a66d 100644 --- a/consensus/log.go +++ b/consensus/log.go @@ -1,7 +1,7 @@ package consensus import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "consensus") diff --git a/consensus/reactor.go b/consensus/reactor.go index b2d2294c..2b449718 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -1,3 +1,4 @@ + package consensus import ( @@ -9,12 +10,12 @@ import ( "time" bc "github.com/tendermint/tendermint/blockchain" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) const ( diff --git a/consensus/state.go b/consensus/state.go index a846f530..61d0bf47 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -159,12 +159,12 @@ import ( acm "github.com/tendermint/tendermint/account" bc "github.com/tendermint/tendermint/blockchain" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" mempl "github.com/tendermint/tendermint/mempool" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) var ( diff --git a/consensus/state_test.go b/consensus/state_test.go index b168041e..ff37f9c3 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -1,3 +1,4 @@ + package consensus import ( diff --git a/consensus/test.go b/consensus/test.go index 2483581b..a05b8ee6 100644 --- a/consensus/test.go +++ b/consensus/test.go @@ -7,10 +7,10 @@ import ( "time" bc "github.com/tendermint/tendermint/blockchain" - dbm "github.com/tendermint/tendermint/db" + dbm "github.com/tendermint/go-db" "github.com/tendermint/tendermint/events" mempl "github.com/tendermint/tendermint/mempool" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" ) diff --git a/crawler/crawl.go b/crawler/crawl.go index a62bd677..b4b26433 100644 --- a/crawler/crawl.go +++ b/crawler/crawl.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ctypes "github.com/tendermint/tendermint/rpc/core/types" cclient "github.com/tendermint/tendermint/rpc/core_client" "github.com/tendermint/tendermint/types" diff --git a/crawler/log.go b/crawler/log.go index 77b9bdfa..14ba849c 100644 --- a/crawler/log.go +++ b/crawler/log.go @@ -1,7 +1,7 @@ package crawler import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" + "github.com/tendermint/log15" ) var log = log15.New("module", "crawler") diff --git a/db/config.go b/db/config.go deleted file mode 100644 index 8c24d2fd..00000000 --- a/db/config.go +++ /dev/null @@ -1,13 +0,0 @@ -package db - -import ( - cfg "github.com/tendermint/tendermint/config" -) - -var config cfg.Config = nil - -func init() { - cfg.OnConfig(func(newConfig cfg.Config) { - config = newConfig - }) -} diff --git a/db/db.go b/db/db.go deleted file mode 100644 index 7c2bdaae..00000000 --- a/db/db.go +++ /dev/null @@ -1,50 +0,0 @@ -package db - -import ( - "path" - - . "github.com/tendermint/tendermint/common" -) - -type DB interface { - Get([]byte) []byte - Set([]byte, []byte) - SetSync([]byte, []byte) - Delete([]byte) - DeleteSync([]byte) - Close() - - // For debugging - Print() -} - -//----------------------------------------------------------------------------- - -// Database types -const DBBackendMemDB = "memdb" -const DBBackendLevelDB = "leveldb" - -var dbs = NewCMap() - -func GetDB(name string) DB { - db := dbs.Get(name) - if db != nil { - return db.(DB) - } - switch config.GetString("db_backend") { - case DBBackendMemDB: - db := NewMemDB() - dbs.Set(name, db) - return db - case DBBackendLevelDB: - db, err := NewLevelDB(path.Join(config.GetString("db_dir"), name+".db")) - if err != nil { - PanicCrisis(err) - } - dbs.Set(name, db) - return db - default: - PanicSanity(Fmt("Unknown DB backend: %v", config.GetString("db_backend"))) - } - return nil -} diff --git a/db/level_db.go b/db/level_db.go deleted file mode 100644 index a8a6735c..00000000 --- a/db/level_db.go +++ /dev/null @@ -1,82 +0,0 @@ -package db - -import ( - "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "path" - - . "github.com/tendermint/tendermint/common" -) - -type LevelDB struct { - db *leveldb.DB -} - -func NewLevelDB(name string) (*LevelDB, error) { - dbPath := path.Join(name) - db, err := leveldb.OpenFile(dbPath, nil) - if err != nil { - return nil, err - } - database := &LevelDB{db: db} - return database, nil -} - -func (db *LevelDB) Get(key []byte) []byte { - res, err := db.db.Get(key, nil) - if err != nil { - if err == errors.ErrNotFound { - return nil - } else { - PanicCrisis(err) - } - } - return res -} - -func (db *LevelDB) Set(key []byte, value []byte) { - err := db.db.Put(key, value, nil) - if err != nil { - PanicCrisis(err) - } -} - -func (db *LevelDB) SetSync(key []byte, value []byte) { - err := db.db.Put(key, value, &opt.WriteOptions{Sync: true}) - if err != nil { - PanicCrisis(err) - } -} - -func (db *LevelDB) Delete(key []byte) { - err := db.db.Delete(key, nil) - if err != nil { - PanicCrisis(err) - } -} - -func (db *LevelDB) DeleteSync(key []byte) { - err := db.db.Delete(key, &opt.WriteOptions{Sync: true}) - if err != nil { - PanicCrisis(err) - } -} - -func (db *LevelDB) DB() *leveldb.DB { - return db.db -} - -func (db *LevelDB) Close() { - db.db.Close() -} - -func (db *LevelDB) Print() { - iter := db.db.NewIterator(nil, nil) - for iter.Next() { - key := iter.Key() - value := iter.Value() - fmt.Printf("[%X]:\t[%X]\n", key, value) - } -} diff --git a/db/mem_db.go b/db/mem_db.go deleted file mode 100644 index b7d8918d..00000000 --- a/db/mem_db.go +++ /dev/null @@ -1,44 +0,0 @@ -package db - -import ( - "fmt" -) - -type MemDB struct { - db map[string][]byte -} - -func NewMemDB() *MemDB { - database := &MemDB{db: make(map[string][]byte)} - return database -} - -func (db *MemDB) Get(key []byte) []byte { - return db.db[string(key)] -} - -func (db *MemDB) Set(key []byte, value []byte) { - db.db[string(key)] = value -} - -func (db *MemDB) SetSync(key []byte, value []byte) { - db.db[string(key)] = value -} - -func (db *MemDB) Delete(key []byte) { - delete(db.db, string(key)) -} - -func (db *MemDB) DeleteSync(key []byte) { - delete(db.db, string(key)) -} - -func (db *MemDB) Close() { - db = nil -} - -func (db *MemDB) Print() { - for key, value := range db.db { - fmt.Printf("[%X]:\t[%X]\n", []byte(key), value) - } -} diff --git a/events/events.go b/events/events.go index a4173d24..05f7115f 100644 --- a/events/events.go +++ b/events/events.go @@ -3,7 +3,7 @@ package events import ( "sync" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/types" ) diff --git a/events/log.go b/events/log.go index 5b301bdf..52546229 100644 --- a/events/log.go +++ b/events/log.go @@ -1,7 +1,7 @@ package events import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "events") diff --git a/logger/config.go b/logger/config.go deleted file mode 100644 index 88eb6b61..00000000 --- a/logger/config.go +++ /dev/null @@ -1,14 +0,0 @@ -package logger - -import ( - cfg "github.com/tendermint/tendermint/config" -) - -var config cfg.Config = nil - -func init() { - cfg.OnConfig(func(newConfig cfg.Config) { - config = newConfig - Reset() // reset log root upon config change. - }) -} diff --git a/logger/log.go b/logger/log.go deleted file mode 100644 index e3ee8dd9..00000000 --- a/logger/log.go +++ /dev/null @@ -1,55 +0,0 @@ -package logger - -import ( - "os" - - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" - . "github.com/tendermint/tendermint/common" -) - -var rootHandler log15.Handler - -func init() { - Reset() -} - -// You might want to call this after resetting tendermint/config. -func Reset() { - - var logLevel string = "debug" - if config != nil { - logLevel = config.GetString("log_level") - } - - // stdout handler - //handlers := []log15.Handler{} - stdoutHandler := log15.LvlFilterHandler( - getLevel(logLevel), - log15.StreamHandler(os.Stdout, log15.TerminalFormat()), - ) - //handlers = append(handlers, stdoutHandler) - - // Set rootHandler. - //rootHandler = log15.MultiHandler(handlers...) - rootHandler = stdoutHandler - - // By setting handlers on the root, we handle events from all loggers. - log15.Root().SetHandler(rootHandler) -} - -// See binary/log for an example of usage. -func RootHandler() log15.Handler { - return rootHandler -} - -func New(ctx ...interface{}) log15.Logger { - return log15.Root().New(ctx...) -} - -func getLevel(lvlString string) log15.Lvl { - lvl, err := log15.LvlFromString(lvlString) - if err != nil { - Exit(Fmt("Invalid log level %v: %v", lvlString, err)) - } - return lvl -} diff --git a/mempool/config.go b/mempool/config.go index 93680308..ffe408d3 100644 --- a/mempool/config.go +++ b/mempool/config.go @@ -1,7 +1,8 @@ + package mempool import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/mempool/log.go b/mempool/log.go index 0bc62b10..dcb2f920 100644 --- a/mempool/log.go +++ b/mempool/log.go @@ -1,7 +1,7 @@ package mempool import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "mempool") diff --git a/mempool/reactor.go b/mempool/reactor.go index bc869390..17f580cd 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -7,12 +7,12 @@ import ( "reflect" "time" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) var ( diff --git a/merkle/README.md b/merkle/README.md deleted file mode 100644 index f7ae879f..00000000 --- a/merkle/README.md +++ /dev/null @@ -1,18 +0,0 @@ -There are two types of merkle trees in this module. - -* IAVL+ Tree: A snapshottable (immutable) AVL+ tree for persistent data -* A simple merkle tree for static data - -## IAVL+ Tree - -The purpose of this data structure is to provide persistent storage for key-value pairs (say to store account balances) such that a deterministic merkle root hash can be computed. The tree is balanced using a variant of the [AVL algortihm](http://en.wikipedia.org/wiki/AVL_tree) so all operations are O(log(n)). - -Nodes of this tree are immutable and indexed by its hash. Thus any node serves as an immutable snapshot which lets us stage uncommitted transactions from the mempool cheaply, and we can instantly roll back to the last committed state to process transactions of a newly committed block (which may not be the same set of transactions as those from the mempool). - -In an AVL tree, the heights of the two child subtrees of any node differ by at most one. Whenever this condition is violated upon an update, the tree is rebalanced by creating O(log(n)) new nodes that point to unmodified nodes of the old tree. In the original AVL algorithm, inner nodes can also hold key-value pairs. The AVL+ algorithm (note the plus) modifies the AVL algorithm to keep all values on leaf nodes, while only using branch-nodes to store keys. This simplifies the algorithm while keeping the merkle hash trail short. - -In Ethereum, the analog is [Patricia tries](http://en.wikipedia.org/wiki/Radix_tree). There are tradeoffs. Keys do not need to be hashed prior to insertion in IAVL+ trees, so this provides faster iteration in the key space which may benefit some applications. The logic is simpler to implement, requiring only two types of nodes -- inner nodes and leaf nodes. On the other hand, while IAVL+ trees provide a deterministic merkle root hash, it depends on the order of transactions. In practice this shouldn't be a problem, since you can efficiently encode the tree structure when serializing the tree contents. - -## Simple Merkle Tree - -For smaller static data structures that don't require immutable snapshots or mutability, use the functions provided in `simple_tree.go`. The transactions and validation signatures of a block are hashed using this simple merkle tree logic. diff --git a/merkle/iavl_node.go b/merkle/iavl_node.go deleted file mode 100644 index 96d8a19c..00000000 --- a/merkle/iavl_node.go +++ /dev/null @@ -1,459 +0,0 @@ -package merkle - -import ( - "bytes" - "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" - "io" - - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" -) - -// Node - -type IAVLNode struct { - key interface{} - value interface{} - height int8 - size int - hash []byte - leftHash []byte - leftNode *IAVLNode - rightHash []byte - rightNode *IAVLNode - persisted bool -} - -func NewIAVLNode(key interface{}, value interface{}) *IAVLNode { - return &IAVLNode{ - key: key, - value: value, - height: 0, - size: 1, - } -} - -// NOTE: The hash is not saved or set. The caller should set the hash afterwards. -// (Presumably the caller already has the hash) -func ReadIAVLNode(t *IAVLTree, r io.Reader, n *int64, err *error) *IAVLNode { - node := &IAVLNode{} - - // node header - node.height = wire.ReadInt8(r, n, err) - node.size = wire.ReadVarint(r, n, err) - node.key = decodeByteSlice(t.keyCodec, r, n, err) - - if node.height == 0 { - // value - node.value = decodeByteSlice(t.valueCodec, r, n, err) - } else { - // children - node.leftHash = wire.ReadByteSlice(r, n, err) - node.rightHash = wire.ReadByteSlice(r, n, err) - } - return node -} - -func (node *IAVLNode) _copy() *IAVLNode { - if node.height == 0 { - PanicSanity("Why are you copying a value node?") - } - return &IAVLNode{ - key: node.key, - height: node.height, - size: node.size, - hash: nil, // Going to be mutated anyways. - leftHash: node.leftHash, - leftNode: node.leftNode, - rightHash: node.rightHash, - rightNode: node.rightNode, - persisted: false, // Going to be mutated, so it can't already be persisted. - } -} - -func (node *IAVLNode) has(t *IAVLTree, key interface{}) (has bool) { - if t.keyCodec.Compare(node.key, key) == 0 { - return true - } - if node.height == 0 { - return false - } else { - if t.keyCodec.Compare(key, node.key) < 0 { - return node.getLeftNode(t).has(t, key) - } else { - return node.getRightNode(t).has(t, key) - } - } -} - -func (node *IAVLNode) get(t *IAVLTree, key interface{}) (index int, value interface{}) { - if node.height == 0 { - if t.keyCodec.Compare(node.key, key) == 0 { - return 0, node.value - } else { - return 0, nil - } - } else { - if t.keyCodec.Compare(key, node.key) < 0 { - return node.getLeftNode(t).get(t, key) - } else { - rightNode := node.getRightNode(t) - index, value = rightNode.get(t, key) - index += node.size - rightNode.size - return index, value - } - } -} - -func (node *IAVLNode) getByIndex(t *IAVLTree, index int) (key interface{}, value interface{}) { - if node.height == 0 { - if index == 0 { - return node.key, node.value - } else { - PanicSanity("getByIndex asked for invalid index") - return nil, nil - } - } else { - // TODO: could improve this by storing the - // sizes as well as left/right hash. - leftNode := node.getLeftNode(t) - if index < leftNode.size { - return leftNode.getByIndex(t, index) - } else { - return node.getRightNode(t).getByIndex(t, index-leftNode.size) - } - } -} - -// NOTE: sets hashes recursively -func (node *IAVLNode) hashWithCount(t *IAVLTree) ([]byte, int) { - if node.hash != nil { - return node.hash, 0 - } - - hasher := ripemd160.New() - buf := new(bytes.Buffer) - _, hashCount, err := node.writeHashBytes(t, buf) - if err != nil { - PanicCrisis(err) - } - // fmt.Printf("Wrote IAVL hash bytes: %X\n", buf.Bytes()) - hasher.Write(buf.Bytes()) - node.hash = hasher.Sum(nil) - // fmt.Printf("Write IAVL hash: %X\n", node.hash) - - return node.hash, hashCount + 1 -} - -// NOTE: sets hashes recursively -func (node *IAVLNode) writeHashBytes(t *IAVLTree, w io.Writer) (n int64, hashCount int, err error) { - // height & size - wire.WriteInt8(node.height, w, &n, &err) - wire.WriteVarint(node.size, w, &n, &err) - // key is not written for inner nodes, unlike writePersistBytes - - if node.height == 0 { - // key & value - encodeByteSlice(node.key, t.keyCodec, w, &n, &err) - encodeByteSlice(node.value, t.valueCodec, w, &n, &err) - } else { - // left - if node.leftNode != nil { - leftHash, leftCount := node.leftNode.hashWithCount(t) - node.leftHash = leftHash - hashCount += leftCount - } - if node.leftHash == nil { - PanicSanity("node.leftHash was nil in writeHashBytes") - } - wire.WriteByteSlice(node.leftHash, w, &n, &err) - // right - if node.rightNode != nil { - rightHash, rightCount := node.rightNode.hashWithCount(t) - node.rightHash = rightHash - hashCount += rightCount - } - if node.rightHash == nil { - PanicSanity("node.rightHash was nil in writeHashBytes") - } - wire.WriteByteSlice(node.rightHash, w, &n, &err) - } - return -} - -// NOTE: sets hashes recursively -// NOTE: clears leftNode/rightNode recursively -func (node *IAVLNode) save(t *IAVLTree) []byte { - if node.hash == nil { - node.hash, _ = node.hashWithCount(t) - } - if node.persisted { - return node.hash - } - - // save children - if node.leftNode != nil { - node.leftHash = node.leftNode.save(t) - node.leftNode = nil - } - if node.rightNode != nil { - node.rightHash = node.rightNode.save(t) - node.rightNode = nil - } - - // save node - t.ndb.SaveNode(t, node) - return node.hash -} - -// NOTE: sets hashes recursively -func (node *IAVLNode) writePersistBytes(t *IAVLTree, w io.Writer) (n int64, err error) { - // node header - wire.WriteInt8(node.height, w, &n, &err) - wire.WriteVarint(node.size, w, &n, &err) - // key (unlike writeHashBytes, key is written for inner nodes) - encodeByteSlice(node.key, t.keyCodec, w, &n, &err) - - if node.height == 0 { - // value - encodeByteSlice(node.value, t.valueCodec, w, &n, &err) - } else { - // left - if node.leftHash == nil { - PanicSanity("node.leftHash was nil in writePersistBytes") - } - wire.WriteByteSlice(node.leftHash, w, &n, &err) - // right - if node.rightHash == nil { - PanicSanity("node.rightHash was nil in writePersistBytes") - } - wire.WriteByteSlice(node.rightHash, w, &n, &err) - } - return -} - -func (node *IAVLNode) set(t *IAVLTree, key interface{}, value interface{}) (newSelf *IAVLNode, updated bool) { - if node.height == 0 { - cmp := t.keyCodec.Compare(key, node.key) - if cmp < 0 { - return &IAVLNode{ - key: node.key, - height: 1, - size: 2, - leftNode: NewIAVLNode(key, value), - rightNode: node, - }, false - } else if cmp == 0 { - return NewIAVLNode(key, value), true - } else { - return &IAVLNode{ - key: key, - height: 1, - size: 2, - leftNode: node, - rightNode: NewIAVLNode(key, value), - }, false - } - } else { - node = node._copy() - if t.keyCodec.Compare(key, node.key) < 0 { - node.leftNode, updated = node.getLeftNode(t).set(t, key, value) - node.leftHash = nil - } else { - node.rightNode, updated = node.getRightNode(t).set(t, key, value) - node.rightHash = nil - } - if updated { - return node, updated - } else { - node.calcHeightAndSize(t) - return node.balance(t), updated - } - } -} - -// newHash/newNode: The new hash or node to replace node after remove. -// newKey: new leftmost leaf key for tree after successfully removing 'key' if changed. -// value: removed value. -func (node *IAVLNode) remove(t *IAVLTree, key interface{}) ( - newHash []byte, newNode *IAVLNode, newKey interface{}, value interface{}, removed bool) { - if node.height == 0 { - if t.keyCodec.Compare(key, node.key) == 0 { - return nil, nil, nil, node.value, true - } else { - return nil, node, nil, nil, false - } - } else { - if t.keyCodec.Compare(key, node.key) < 0 { - var newLeftHash []byte - var newLeftNode *IAVLNode - newLeftHash, newLeftNode, newKey, value, removed = node.getLeftNode(t).remove(t, key) - if !removed { - return nil, node, nil, value, false - } else if newLeftHash == nil && newLeftNode == nil { // left node held value, was removed - return node.rightHash, node.rightNode, node.key, value, true - } - node = node._copy() - node.leftHash, node.leftNode = newLeftHash, newLeftNode - node.calcHeightAndSize(t) - return nil, node.balance(t), newKey, value, true - } else { - var newRightHash []byte - var newRightNode *IAVLNode - newRightHash, newRightNode, newKey, value, removed = node.getRightNode(t).remove(t, key) - if !removed { - return nil, node, nil, value, false - } else if newRightHash == nil && newRightNode == nil { // right node held value, was removed - return node.leftHash, node.leftNode, nil, value, true - } - node = node._copy() - node.rightHash, node.rightNode = newRightHash, newRightNode - if newKey != nil { - node.key = newKey - newKey = nil - } - node.calcHeightAndSize(t) - return nil, node.balance(t), newKey, value, true - } - } -} - -func (node *IAVLNode) getLeftNode(t *IAVLTree) *IAVLNode { - if node.leftNode != nil { - return node.leftNode - } else { - return t.ndb.GetNode(t, node.leftHash) - } -} - -func (node *IAVLNode) getRightNode(t *IAVLTree) *IAVLNode { - if node.rightNode != nil { - return node.rightNode - } else { - return t.ndb.GetNode(t, node.rightHash) - } -} - -func (node *IAVLNode) rotateRight(t *IAVLTree) *IAVLNode { - node = node._copy() - sl := node.getLeftNode(t)._copy() - - slrHash, slrCached := sl.rightHash, sl.rightNode - sl.rightHash, sl.rightNode = nil, node - node.leftHash, node.leftNode = slrHash, slrCached - - node.calcHeightAndSize(t) - sl.calcHeightAndSize(t) - - return sl -} - -func (node *IAVLNode) rotateLeft(t *IAVLTree) *IAVLNode { - node = node._copy() - sr := node.getRightNode(t)._copy() - - srlHash, srlCached := sr.leftHash, sr.leftNode - sr.leftHash, sr.leftNode = nil, node - node.rightHash, node.rightNode = srlHash, srlCached - - node.calcHeightAndSize(t) - sr.calcHeightAndSize(t) - - return sr -} - -// NOTE: mutates height and size -func (node *IAVLNode) calcHeightAndSize(t *IAVLTree) { - node.height = maxInt8(node.getLeftNode(t).height, node.getRightNode(t).height) + 1 - node.size = node.getLeftNode(t).size + node.getRightNode(t).size -} - -func (node *IAVLNode) calcBalance(t *IAVLTree) int { - return int(node.getLeftNode(t).height) - int(node.getRightNode(t).height) -} - -func (node *IAVLNode) balance(t *IAVLTree) (newSelf *IAVLNode) { - balance := node.calcBalance(t) - if balance > 1 { - if node.getLeftNode(t).calcBalance(t) >= 0 { - // Left Left Case - return node.rotateRight(t) - } else { - // Left Right Case - node = node._copy() - node.leftHash, node.leftNode = nil, node.getLeftNode(t).rotateLeft(t) - //node.calcHeightAndSize() - return node.rotateRight(t) - } - } - if balance < -1 { - if node.getRightNode(t).calcBalance(t) <= 0 { - // Right Right Case - return node.rotateLeft(t) - } else { - // Right Left Case - node = node._copy() - node.rightHash, node.rightNode = nil, node.getRightNode(t).rotateRight(t) - //node.calcHeightAndSize() - return node.rotateLeft(t) - } - } - // Nothing changed - return node -} - -func (node *IAVLNode) traverse(t *IAVLTree, cb func(*IAVLNode) bool) bool { - stop := cb(node) - if stop { - return stop - } - if node.height > 0 { - stop = node.getLeftNode(t).traverse(t, cb) - if stop { - return stop - } - stop = node.getRightNode(t).traverse(t, cb) - if stop { - return stop - } - } - return false -} - -// Only used in testing... -func (node *IAVLNode) lmd(t *IAVLTree) *IAVLNode { - if node.height == 0 { - return node - } - return node.getLeftNode(t).lmd(t) -} - -// Only used in testing... -func (node *IAVLNode) rmd(t *IAVLTree) *IAVLNode { - if node.height == 0 { - return node - } - return node.getRightNode(t).rmd(t) -} - -//-------------------------------------------------------------------------------- - -// Read a (length prefixed) byteslice then decode the object using the codec -func decodeByteSlice(codec wire.Codec, r io.Reader, n *int64, err *error) interface{} { - bytez := wire.ReadByteSlice(r, n, err) - if *err != nil { - return nil - } - n_ := new(int64) - return codec.Decode(bytes.NewBuffer(bytez), n_, err) -} - -// Encode object using codec, then write a (length prefixed) byteslice. -func encodeByteSlice(o interface{}, codec wire.Codec, w io.Writer, n *int64, err *error) { - buf, n_ := new(bytes.Buffer), new(int64) - codec.Encode(o, buf, n_, err) - if *err != nil { - return - } - wire.WriteByteSlice(buf.Bytes(), w, n, err) -} diff --git a/merkle/iavl_proof.go b/merkle/iavl_proof.go deleted file mode 100644 index 2f4f7763..00000000 --- a/merkle/iavl_proof.go +++ /dev/null @@ -1,151 +0,0 @@ -package merkle - -import ( - "bytes" - - "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" - - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" -) - -type IAVLProof struct { - LeafNode IAVLProofLeafNode - InnerNodes []IAVLProofInnerNode - RootHash []byte -} - -func (proof *IAVLProof) Verify(keyBytes, valueBytes, rootHash []byte) bool { - if !bytes.Equal(keyBytes, proof.LeafNode.KeyBytes) { - return false - } - if !bytes.Equal(valueBytes, proof.LeafNode.ValueBytes) { - return false - } - if !bytes.Equal(rootHash, proof.RootHash) { - return false - } - hash := proof.LeafNode.Hash() - // fmt.Printf("leaf hash: %X\n", hash) - for _, branch := range proof.InnerNodes { - hash = branch.Hash(hash) - // fmt.Printf("branch hash: %X\n", hash) - } - // fmt.Printf("root: %X, computed: %X\n", proof.RootHash, hash) - return bytes.Equal(proof.RootHash, hash) -} - -type IAVLProofInnerNode struct { - Height int8 - Size int - Left []byte - Right []byte -} - -func (branch IAVLProofInnerNode) Hash(childHash []byte) []byte { - hasher := ripemd160.New() - buf := new(bytes.Buffer) - n, err := int64(0), error(nil) - wire.WriteInt8(branch.Height, buf, &n, &err) - wire.WriteVarint(branch.Size, buf, &n, &err) - if len(branch.Left) == 0 { - wire.WriteByteSlice(childHash, buf, &n, &err) - wire.WriteByteSlice(branch.Right, buf, &n, &err) - } else { - wire.WriteByteSlice(branch.Left, buf, &n, &err) - wire.WriteByteSlice(childHash, buf, &n, &err) - } - if err != nil { - PanicCrisis(Fmt("Failed to hash IAVLProofInnerNode: %v", err)) - } - // fmt.Printf("InnerNode hash bytes: %X\n", buf.Bytes()) - hasher.Write(buf.Bytes()) - return hasher.Sum(nil) -} - -type IAVLProofLeafNode struct { - KeyBytes []byte - ValueBytes []byte -} - -func (leaf IAVLProofLeafNode) Hash() []byte { - hasher := ripemd160.New() - buf := new(bytes.Buffer) - n, err := int64(0), error(nil) - wire.WriteInt8(0, buf, &n, &err) - wire.WriteVarint(1, buf, &n, &err) - wire.WriteByteSlice(leaf.KeyBytes, buf, &n, &err) - wire.WriteByteSlice(leaf.ValueBytes, buf, &n, &err) - if err != nil { - PanicCrisis(Fmt("Failed to hash IAVLProofLeafNode: %v", err)) - } - // fmt.Printf("LeafNode hash bytes: %X\n", buf.Bytes()) - hasher.Write(buf.Bytes()) - return hasher.Sum(nil) -} - -func (node *IAVLNode) constructProof(t *IAVLTree, key interface{}, proof *IAVLProof) (exists bool) { - if node.height == 0 { - if t.keyCodec.Compare(node.key, key) == 0 { - keyBuf, valueBuf := new(bytes.Buffer), new(bytes.Buffer) - n, err := int64(0), error(nil) - t.keyCodec.Encode(node.key, keyBuf, &n, &err) - if err != nil { - PanicCrisis(Fmt("Failed to encode node.key: %v", err)) - } - t.valueCodec.Encode(node.value, valueBuf, &n, &err) - if err != nil { - PanicCrisis(Fmt("Failed to encode node.value: %v", err)) - } - leaf := IAVLProofLeafNode{ - KeyBytes: keyBuf.Bytes(), - ValueBytes: valueBuf.Bytes(), - } - proof.LeafNode = leaf - return true - } else { - return false - } - } else { - if t.keyCodec.Compare(key, node.key) < 0 { - exists := node.getLeftNode(t).constructProof(t, key, proof) - if !exists { - return false - } - branch := IAVLProofInnerNode{ - Height: node.height, - Size: node.size, - Left: nil, - Right: node.getRightNode(t).hash, - } - proof.InnerNodes = append(proof.InnerNodes, branch) - return true - } else { - exists := node.getRightNode(t).constructProof(t, key, proof) - if !exists { - return false - } - branch := IAVLProofInnerNode{ - Height: node.height, - Size: node.size, - Left: node.getLeftNode(t).hash, - Right: nil, - } - proof.InnerNodes = append(proof.InnerNodes, branch) - return true - } - } -} - -// Returns nil if key is not in tree. -func (t *IAVLTree) ConstructProof(key interface{}) *IAVLProof { - if t.root == nil { - return nil - } - t.root.hashWithCount(t) // Ensure that all hashes are calculated. - proof := &IAVLProof{ - RootHash: t.root.hash, - } - t.root.constructProof(t, key, proof) - return proof -} diff --git a/merkle/iavl_test.go b/merkle/iavl_test.go deleted file mode 100644 index 889f8e1b..00000000 --- a/merkle/iavl_test.go +++ /dev/null @@ -1,335 +0,0 @@ -package merkle - -import ( - "bytes" - "fmt" - - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" - . "github.com/tendermint/tendermint/common/test" - "github.com/tendermint/tendermint/db" - - "runtime" - "testing" -) - -func randstr(length int) string { - return RandStr(length) -} - -// Convenience for a new node -func N(l, r interface{}) *IAVLNode { - var left, right *IAVLNode - if _, ok := l.(*IAVLNode); ok { - left = l.(*IAVLNode) - } else { - left = NewIAVLNode(l, "") - } - if _, ok := r.(*IAVLNode); ok { - right = r.(*IAVLNode) - } else { - right = NewIAVLNode(r, "") - } - - n := &IAVLNode{ - key: right.lmd(nil).key, - value: "", - leftNode: left, - rightNode: right, - } - n.calcHeightAndSize(nil) - return n -} - -// Setup a deep node -func T(n *IAVLNode) *IAVLTree { - t := NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 0, nil) - n.hashWithCount(t) - t.root = n - return t -} - -// Convenience for simple printing of keys & tree structure -func P(n *IAVLNode) string { - if n.height == 0 { - return fmt.Sprintf("%v", n.key) - } else { - return fmt.Sprintf("(%v %v)", P(n.leftNode), P(n.rightNode)) - } -} - -func TestUnit(t *testing.T) { - - expectHash := func(tree *IAVLTree, hashCount int) { - // ensure number of new hash calculations is as expected. - hash, count := tree.HashWithCount() - if count != hashCount { - t.Fatalf("Expected %v new hashes, got %v", hashCount, count) - } - // nuke hashes and reconstruct hash, ensure it's the same. - tree.root.traverse(tree, func(node *IAVLNode) bool { - node.hash = nil - return false - }) - // ensure that the new hash after nuking is the same as the old. - newHash, _ := tree.HashWithCount() - if bytes.Compare(hash, newHash) != 0 { - t.Fatalf("Expected hash %v but got %v after nuking", hash, newHash) - } - } - - expectSet := func(tree *IAVLTree, i int, repr string, hashCount int) { - origNode := tree.root - updated := tree.Set(i, "") - // ensure node was added & structure is as expected. - if updated == true || P(tree.root) != repr { - t.Fatalf("Adding %v to %v:\nExpected %v\nUnexpectedly got %v updated:%v", - i, P(origNode), repr, P(tree.root), updated) - } - // ensure hash calculation requirements - expectHash(tree, hashCount) - tree.root = origNode - } - - expectRemove := func(tree *IAVLTree, i int, repr string, hashCount int) { - origNode := tree.root - value, removed := tree.Remove(i) - // ensure node was added & structure is as expected. - if value != "" || !removed || P(tree.root) != repr { - t.Fatalf("Removing %v from %v:\nExpected %v\nUnexpectedly got %v value:%v removed:%v", - i, P(origNode), repr, P(tree.root), value, removed) - } - // ensure hash calculation requirements - expectHash(tree, hashCount) - tree.root = origNode - } - - //////// Test Set cases: - - // Case 1: - t1 := T(N(4, 20)) - - expectSet(t1, 8, "((4 8) 20)", 3) - expectSet(t1, 25, "(4 (20 25))", 3) - - t2 := T(N(4, N(20, 25))) - - expectSet(t2, 8, "((4 8) (20 25))", 3) - expectSet(t2, 30, "((4 20) (25 30))", 4) - - t3 := T(N(N(1, 2), 6)) - - expectSet(t3, 4, "((1 2) (4 6))", 4) - expectSet(t3, 8, "((1 2) (6 8))", 3) - - t4 := T(N(N(1, 2), N(N(5, 6), N(7, 9)))) - - expectSet(t4, 8, "(((1 2) (5 6)) ((7 8) 9))", 5) - expectSet(t4, 10, "(((1 2) (5 6)) (7 (9 10)))", 5) - - //////// Test Remove cases: - - t10 := T(N(N(1, 2), 3)) - - expectRemove(t10, 2, "(1 3)", 1) - expectRemove(t10, 3, "(1 2)", 0) - - t11 := T(N(N(N(1, 2), 3), N(4, 5))) - - expectRemove(t11, 4, "((1 2) (3 5))", 2) - expectRemove(t11, 3, "((1 2) (4 5))", 1) - -} - -func TestIntegration(t *testing.T) { - - type record struct { - key string - value string - } - - records := make([]*record, 400) - var tree *IAVLTree = NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 0, nil) - - randomRecord := func() *record { - return &record{randstr(20), randstr(20)} - } - - for i := range records { - r := randomRecord() - records[i] = r - //t.Log("New record", r) - //PrintIAVLNode(tree.root) - updated := tree.Set(r.key, "") - if updated { - t.Error("should have not been updated") - } - updated = tree.Set(r.key, r.value) - if !updated { - t.Error("should have been updated") - } - if tree.Size() != i+1 { - t.Error("size was wrong", tree.Size(), i+1) - } - } - - for _, r := range records { - if has := tree.Has(r.key); !has { - t.Error("Missing key", r.key) - } - if has := tree.Has(randstr(12)); has { - t.Error("Table has extra key") - } - if _, val := tree.Get(r.key); val.(string) != r.value { - t.Error("wrong value") - } - } - - for i, x := range records { - if val, removed := tree.Remove(x.key); !removed { - t.Error("Wasn't removed") - } else if val != x.value { - t.Error("Wrong value") - } - for _, r := range records[i+1:] { - if has := tree.Has(r.key); !has { - t.Error("Missing key", r.key) - } - if has := tree.Has(randstr(12)); has { - t.Error("Table has extra key") - } - _, val := tree.Get(r.key) - if val != r.value { - t.Error("wrong value") - } - } - if tree.Size() != len(records)-(i+1) { - t.Error("size was wrong", tree.Size(), (len(records) - (i + 1))) - } - } -} - -func TestPersistence(t *testing.T) { - db := db.NewMemDB() - - // Create some random key value pairs - records := make(map[string]string) - for i := 0; i < 10000; i++ { - records[randstr(20)] = randstr(20) - } - - // Construct some tree and save it - t1 := NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 0, db) - for key, value := range records { - t1.Set(key, value) - } - t1.Save() - - hash, _ := t1.HashWithCount() - - // Load a tree - t2 := NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 0, db) - t2.Load(hash) - for key, value := range records { - _, t2value := t2.Get(key) - if t2value != value { - t.Fatalf("Invalid value. Expected %v, got %v", value, t2value) - } - } -} - -func testProof(t *testing.T, proof *IAVLProof, keyBytes, valueBytes, rootHash []byte) { - // Proof must verify. - if !proof.Verify(keyBytes, valueBytes, rootHash) { - t.Errorf("Invalid proof. Verification failed.") - return - } - // Write/Read then verify. - proofBytes := wire.BinaryBytes(proof) - n, err := int64(0), error(nil) - proof2 := wire.ReadBinary(&IAVLProof{}, bytes.NewBuffer(proofBytes), &n, &err).(*IAVLProof) - if err != nil { - t.Errorf("Failed to read IAVLProof from bytes: %v", err) - return - } - if !proof2.Verify(keyBytes, valueBytes, rootHash) { - // t.Log(Fmt("%X\n%X\n", proofBytes, wire.BinaryBytes(proof2))) - t.Errorf("Invalid proof after write/read. Verification failed.") - return - } - // Random mutations must not verify - for i := 0; i < 5; i++ { - badProofBytes := MutateByteSlice(proofBytes) - n, err := int64(0), error(nil) - badProof := wire.ReadBinary(&IAVLProof{}, bytes.NewBuffer(badProofBytes), &n, &err).(*IAVLProof) - if err != nil { - continue // This is fine. - } - if badProof.Verify(keyBytes, valueBytes, rootHash) { - t.Errorf("Proof was still valid after a random mutation:\n%X\n%X", proofBytes, badProofBytes) - } - } -} - -func TestIAVLProof(t *testing.T) { - - // Convenient wrapper around wire.BasicCodec. - toBytes := func(o interface{}) []byte { - buf, n, err := new(bytes.Buffer), int64(0), error(nil) - wire.BasicCodec.Encode(o, buf, &n, &err) - if err != nil { - panic(Fmt("Failed to encode thing: %v", err)) - } - return buf.Bytes() - } - - // Construct some random tree - db := db.NewMemDB() - var tree *IAVLTree = NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 100, db) - for i := 0; i < 1000; i++ { - key, value := randstr(20), randstr(20) - tree.Set(key, value) - } - - // Persist the items so far - tree.Save() - - // Add more items so it's not all persisted - for i := 0; i < 100; i++ { - key, value := randstr(20), randstr(20) - tree.Set(key, value) - } - - // Now for each item, construct a proof and verify - tree.Iterate(func(key interface{}, value interface{}) bool { - proof := tree.ConstructProof(key) - if !bytes.Equal(proof.RootHash, tree.Hash()) { - t.Errorf("Invalid proof. Expected root %X, got %X", tree.Hash(), proof.RootHash) - } - testProof(t, proof, toBytes(key), toBytes(value), tree.Hash()) - return false - }) - -} - -func BenchmarkImmutableAvlTree(b *testing.B) { - b.StopTimer() - - t := NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 0, nil) - // 23000ns/op, 43000ops/s - // for i := 0; i < 10000000; i++ { - for i := 0; i < 1000000; i++ { - t.Set(RandInt64(), "") - } - - fmt.Println("ok, starting") - - runtime.GC() - - b.StartTimer() - for i := 0; i < b.N; i++ { - ri := RandInt64() - t.Set(ri, "") - t.Remove(ri) - } -} diff --git a/merkle/iavl_tree.go b/merkle/iavl_tree.go deleted file mode 100644 index 9ea02295..00000000 --- a/merkle/iavl_tree.go +++ /dev/null @@ -1,262 +0,0 @@ -package merkle - -import ( - "bytes" - "container/list" - "sync" - - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" - dbm "github.com/tendermint/tendermint/db" -) - -/* -Immutable AVL Tree (wraps the Node root) -This tree is not goroutine safe. -*/ -type IAVLTree struct { - keyCodec wire.Codec - valueCodec wire.Codec - root *IAVLNode - ndb *nodeDB -} - -func NewIAVLTree(keyCodec, valueCodec wire.Codec, cacheSize int, db dbm.DB) *IAVLTree { - if db == nil { - // In-memory IAVLTree - return &IAVLTree{ - keyCodec: keyCodec, - valueCodec: valueCodec, - } - } else { - // Persistent IAVLTree - return &IAVLTree{ - keyCodec: keyCodec, - valueCodec: valueCodec, - ndb: newNodeDB(cacheSize, db), - } - } -} - -// The returned tree and the original tree are goroutine independent. -// That is, they can each run in their own goroutine. -func (t *IAVLTree) Copy() Tree { - if t.root == nil { - return &IAVLTree{ - keyCodec: t.keyCodec, - valueCodec: t.valueCodec, - root: nil, - ndb: t.ndb, - } - } - if t.ndb != nil && !t.root.persisted { - // Saving a tree finalizes all the nodes. - // It sets all the hashes recursively, - // clears all the leftNode/rightNode values recursively, - // and all the .persisted flags get set. - PanicSanity("It is unsafe to Copy() an unpersisted tree.") - } else if t.ndb == nil && t.root.hash == nil { - // An in-memory IAVLTree is finalized when the hashes are - // calculated. - t.root.hashWithCount(t) - } - return &IAVLTree{ - keyCodec: t.keyCodec, - valueCodec: t.valueCodec, - root: t.root, - ndb: t.ndb, - } -} - -func (t *IAVLTree) Size() int { - if t.root == nil { - return 0 - } - return t.root.size -} - -func (t *IAVLTree) Height() int8 { - if t.root == nil { - return 0 - } - return t.root.height -} - -func (t *IAVLTree) Has(key interface{}) bool { - if t.root == nil { - return false - } - return t.root.has(t, key) -} - -func (t *IAVLTree) Set(key interface{}, value interface{}) (updated bool) { - if t.root == nil { - t.root = NewIAVLNode(key, value) - return false - } - t.root, updated = t.root.set(t, key, value) - return updated -} - -func (t *IAVLTree) Hash() []byte { - if t.root == nil { - return nil - } - hash, _ := t.root.hashWithCount(t) - return hash -} - -func (t *IAVLTree) HashWithCount() ([]byte, int) { - if t.root == nil { - return nil, 0 - } - return t.root.hashWithCount(t) -} - -func (t *IAVLTree) Save() []byte { - if t.root == nil { - return nil - } - return t.root.save(t) -} - -// Sets the root node by reading from db. -// If the hash is empty, then sets root to nil. -func (t *IAVLTree) Load(hash []byte) { - if len(hash) == 0 { - t.root = nil - } else { - t.root = t.ndb.GetNode(t, hash) - } -} - -func (t *IAVLTree) Get(key interface{}) (index int, value interface{}) { - if t.root == nil { - return 0, nil - } - return t.root.get(t, key) -} - -func (t *IAVLTree) GetByIndex(index int) (key interface{}, value interface{}) { - if t.root == nil { - return nil, nil - } - return t.root.getByIndex(t, index) -} - -func (t *IAVLTree) Remove(key interface{}) (value interface{}, removed bool) { - if t.root == nil { - return nil, false - } - newRootHash, newRoot, _, value, removed := t.root.remove(t, key) - if !removed { - return nil, false - } - if newRoot == nil && newRootHash != nil { - t.root = t.ndb.GetNode(t, newRootHash) - } else { - t.root = newRoot - } - return value, true -} - -func (t *IAVLTree) Iterate(fn func(key interface{}, value interface{}) bool) (stopped bool) { - if t.root == nil { - return false - } - return t.root.traverse(t, func(node *IAVLNode) bool { - if node.height == 0 { - return fn(node.key, node.value) - } else { - return false - } - }) -} - -//----------------------------------------------------------------------------- - -type nodeElement struct { - node *IAVLNode - elem *list.Element -} - -type nodeDB struct { - mtx sync.Mutex - cache map[string]nodeElement - cacheSize int - cacheQueue *list.List - db dbm.DB -} - -func newNodeDB(cacheSize int, db dbm.DB) *nodeDB { - return &nodeDB{ - cache: make(map[string]nodeElement), - cacheSize: cacheSize, - cacheQueue: list.New(), - db: db, - } -} - -func (ndb *nodeDB) GetNode(t *IAVLTree, hash []byte) *IAVLNode { - ndb.mtx.Lock() - defer ndb.mtx.Unlock() - // Check the cache. - nodeElem, ok := ndb.cache[string(hash)] - if ok { - // Already exists. Move to back of cacheQueue. - ndb.cacheQueue.MoveToBack(nodeElem.elem) - return nodeElem.node - } else { - // Doesn't exist, load. - buf := ndb.db.Get(hash) - if len(buf) == 0 { - ndb.db.(*dbm.LevelDB).Print() - PanicSanity(Fmt("Value missing for key %X", hash)) - } - r := bytes.NewReader(buf) - var n int64 - var err error - node := ReadIAVLNode(t, r, &n, &err) - if err != nil { - PanicCrisis(Fmt("Error reading IAVLNode. bytes: %X error: %v", buf, err)) - } - node.hash = hash - node.persisted = true - ndb.cacheNode(node) - return node - } -} - -func (ndb *nodeDB) SaveNode(t *IAVLTree, node *IAVLNode) { - ndb.mtx.Lock() - defer ndb.mtx.Unlock() - if node.hash == nil { - PanicSanity("Expected to find node.hash, but none found.") - } - if node.persisted { - PanicSanity("Shouldn't be calling save on an already persisted node.") - } - /*if _, ok := ndb.cache[string(node.hash)]; ok { - panic("Shouldn't be calling save on an already cached node.") - }*/ - // Save node bytes to db - buf := bytes.NewBuffer(nil) - _, err := node.writePersistBytes(t, buf) - if err != nil { - PanicCrisis(err) - } - ndb.db.Set(node.hash, buf.Bytes()) - node.persisted = true - ndb.cacheNode(node) -} - -func (ndb *nodeDB) cacheNode(node *IAVLNode) { - // Create entry in cache and append to cacheQueue. - elem := ndb.cacheQueue.PushBack(node.hash) - ndb.cache[string(node.hash)] = nodeElement{node, elem} - // Maybe expire an item. - if ndb.cacheQueue.Len() > ndb.cacheSize { - hash := ndb.cacheQueue.Remove(ndb.cacheQueue.Front()).([]byte) - delete(ndb.cache, string(hash)) - } -} diff --git a/merkle/simple_tree.go b/merkle/simple_tree.go deleted file mode 100644 index 5a7afdf6..00000000 --- a/merkle/simple_tree.go +++ /dev/null @@ -1,298 +0,0 @@ -/* -Computes a deterministic minimal height merkle tree hash. -If the number of items is not a power of two, some leaves -will be at different levels. Tries to keep both sides of -the tree the same size, but the left may be one greater. - -Use this for short deterministic trees, such as the validator list. -For larger datasets, use IAVLTree. - - * - / \ - / \ - / \ - / \ - * * - / \ / \ - / \ / \ - / \ / \ - * * * h6 - / \ / \ / \ - h0 h1 h2 h3 h4 h5 - -*/ - -package merkle - -import ( - "bytes" - "fmt" - "sort" - - "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" - - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" -) - -func SimpleHashFromTwoHashes(left []byte, right []byte) []byte { - var n int64 - var err error - var hasher = ripemd160.New() - wire.WriteByteSlice(left, hasher, &n, &err) - wire.WriteByteSlice(right, hasher, &n, &err) - if err != nil { - PanicCrisis(err) - } - return hasher.Sum(nil) -} - -func SimpleHashFromHashes(hashes [][]byte) []byte { - // Recursive impl. - switch len(hashes) { - case 0: - return nil - case 1: - return hashes[0] - default: - left := SimpleHashFromHashes(hashes[:(len(hashes)+1)/2]) - right := SimpleHashFromHashes(hashes[(len(hashes)+1)/2:]) - return SimpleHashFromTwoHashes(left, right) - } -} - -// Convenience for SimpleHashFromHashes. -func SimpleHashFromBinaries(items []interface{}) []byte { - hashes := [][]byte{} - for _, item := range items { - hashes = append(hashes, SimpleHashFromBinary(item)) - } - return SimpleHashFromHashes(hashes) -} - -// General Convenience -func SimpleHashFromBinary(item interface{}) []byte { - hasher, n, err := ripemd160.New(), new(int64), new(error) - wire.WriteBinary(item, hasher, n, err) - if *err != nil { - PanicCrisis(err) - } - return hasher.Sum(nil) -} - -// Convenience for SimpleHashFromHashes. -func SimpleHashFromHashables(items []Hashable) []byte { - hashes := [][]byte{} - for _, item := range items { - hash := item.Hash() - hashes = append(hashes, hash) - } - return SimpleHashFromHashes(hashes) -} - -// Convenience for SimpleHashFromHashes. -func SimpleHashFromMap(m map[string]interface{}) []byte { - kpPairsH := MakeSortedKVPairs(m) - return SimpleHashFromHashables(kpPairsH) -} - -//-------------------------------------------------------------------------------- - -/* Convenience struct for key-value pairs. -A list of KVPairs is hashed via `SimpleHashFromHashables`. -NOTE: Each `Value` is encoded for hashing without extra type information, -so the user is presumed to be aware of the Value types. -*/ -type KVPair struct { - Key string - Value interface{} -} - -func (kv KVPair) Hash() []byte { - hasher, n, err := ripemd160.New(), new(int64), new(error) - wire.WriteString(kv.Key, hasher, n, err) - if kvH, ok := kv.Value.(Hashable); ok { - wire.WriteByteSlice(kvH.Hash(), hasher, n, err) - } else { - wire.WriteBinary(kv.Value, hasher, n, err) - } - if *err != nil { - PanicSanity(*err) - } - return hasher.Sum(nil) -} - -type KVPairs []KVPair - -func (kvps KVPairs) Len() int { return len(kvps) } -func (kvps KVPairs) Less(i, j int) bool { return kvps[i].Key < kvps[j].Key } -func (kvps KVPairs) Swap(i, j int) { kvps[i], kvps[j] = kvps[j], kvps[i] } -func (kvps KVPairs) Sort() { sort.Sort(kvps) } - -func MakeSortedKVPairs(m map[string]interface{}) []Hashable { - kvPairs := []KVPair{} - for k, v := range m { - kvPairs = append(kvPairs, KVPair{k, v}) - } - KVPairs(kvPairs).Sort() - kvPairsH := []Hashable{} - for _, kvp := range kvPairs { - kvPairsH = append(kvPairsH, kvp) - } - return kvPairsH -} - -//-------------------------------------------------------------------------------- - -type SimpleProof struct { - Index int `json:"index"` - Total int `json:"total"` - LeafHash []byte `json:"leaf_hash"` - InnerHashes [][]byte `json:"inner_hashes"` // Hashes from leaf's sibling to a root's child. - RootHash []byte `json:"root_hash"` -} - -// proofs[0] is the proof for items[0]. -func SimpleProofsFromHashables(items []Hashable) (proofs []*SimpleProof) { - trails, root := trailsFromHashables(items) - proofs = make([]*SimpleProof, len(items)) - for i, trail := range trails { - proofs[i] = &SimpleProof{ - Index: i, - Total: len(items), - LeafHash: trail.Hash, - InnerHashes: trail.FlattenInnerHashes(), - RootHash: root.Hash, - } - } - return -} - -// Verify that leafHash is a leaf hash of the simple-merkle-tree -// which hashes to rootHash. -func (sp *SimpleProof) Verify(leafHash []byte, rootHash []byte) bool { - if !bytes.Equal(leafHash, sp.LeafHash) { - return false - } - if !bytes.Equal(rootHash, sp.RootHash) { - return false - } - computedHash := computeHashFromInnerHashes(sp.Index, sp.Total, sp.LeafHash, sp.InnerHashes) - if computedHash == nil { - return false - } - if !bytes.Equal(computedHash, rootHash) { - return false - } - return true -} - -func (sp *SimpleProof) String() string { - return sp.StringIndented("") -} - -func (sp *SimpleProof) StringIndented(indent string) string { - return fmt.Sprintf(`SimpleProof{ -%s Index: %v -%s Total: %v -%s LeafHash: %X -%s InnerHashes: %X -%s RootHash: %X -%s}`, - indent, sp.Index, - indent, sp.Total, - indent, sp.LeafHash, - indent, sp.InnerHashes, - indent, sp.RootHash, - indent) -} - -// Use the leafHash and innerHashes to get the root merkle hash. -// If the length of the innerHashes slice isn't exactly correct, the result is nil. -func computeHashFromInnerHashes(index int, total int, leafHash []byte, innerHashes [][]byte) []byte { - // Recursive impl. - if index >= total { - return nil - } - switch total { - case 0: - PanicSanity("Cannot call computeHashFromInnerHashes() with 0 total") - return nil - case 1: - if len(innerHashes) != 0 { - return nil - } - return leafHash - default: - if len(innerHashes) == 0 { - return nil - } - numLeft := (total + 1) / 2 - if index < numLeft { - leftHash := computeHashFromInnerHashes(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1]) - if leftHash == nil { - return nil - } - return SimpleHashFromTwoHashes(leftHash, innerHashes[len(innerHashes)-1]) - } else { - rightHash := computeHashFromInnerHashes(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1]) - if rightHash == nil { - return nil - } - return SimpleHashFromTwoHashes(innerHashes[len(innerHashes)-1], rightHash) - } - } -} - -// Helper structure to construct merkle proof. -// The node and the tree is thrown away afterwards. -// Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil. -// node.Parent.Hash = hash(node.Hash, node.Right.Hash) or -// hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child. -type SimpleProofNode struct { - Hash []byte - Parent *SimpleProofNode - Left *SimpleProofNode // Left sibling (only one of Left,Right is set) - Right *SimpleProofNode // Right sibling (only one of Left,Right is set) -} - -// Starting from a leaf SimpleProofNode, FlattenInnerHashes() will return -// the inner hashes for the item corresponding to the leaf. -func (spn *SimpleProofNode) FlattenInnerHashes() [][]byte { - // Nonrecursive impl. - innerHashes := [][]byte{} - for spn != nil { - if spn.Left != nil { - innerHashes = append(innerHashes, spn.Left.Hash) - } else if spn.Right != nil { - innerHashes = append(innerHashes, spn.Right.Hash) - } else { - break - } - spn = spn.Parent - } - return innerHashes -} - -// trails[0].Hash is the leaf hash for items[0]. -// trails[i].Parent.Parent....Parent == root for all i. -func trailsFromHashables(items []Hashable) (trails []*SimpleProofNode, root *SimpleProofNode) { - // Recursive impl. - switch len(items) { - case 0: - return nil, nil - case 1: - trail := &SimpleProofNode{items[0].Hash(), nil, nil, nil} - return []*SimpleProofNode{trail}, trail - default: - lefts, leftRoot := trailsFromHashables(items[:(len(items)+1)/2]) - rights, rightRoot := trailsFromHashables(items[(len(items)+1)/2:]) - rootHash := SimpleHashFromTwoHashes(leftRoot.Hash, rightRoot.Hash) - root := &SimpleProofNode{rootHash, nil, nil, nil} - leftRoot.Parent = root - leftRoot.Right = rightRoot - rightRoot.Parent = root - rightRoot.Left = leftRoot - return append(lefts, rights...), root - } -} diff --git a/merkle/simple_tree_test.go b/merkle/simple_tree_test.go deleted file mode 100644 index af6ff4df..00000000 --- a/merkle/simple_tree_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package merkle - -import ( - "bytes" - - . "github.com/tendermint/tendermint/common" - . "github.com/tendermint/tendermint/common/test" - - "fmt" - "testing" -) - -type testItem []byte - -func (tI testItem) Hash() []byte { - return []byte(tI) -} - -func TestSimpleProof(t *testing.T) { - - numItems := 100 - - items := make([]Hashable, numItems) - for i := 0; i < numItems; i++ { - items[i] = testItem(RandBytes(32)) - } - - rootHash := SimpleHashFromHashables(items) - - proofs := SimpleProofsFromHashables(items) - - // For each item, check the trail. - for i, item := range items { - itemHash := item.Hash() - proof := proofs[i] - - // Verify success - ok := proof.Verify(itemHash, rootHash) - if !ok { - t.Errorf("Verification failed for index %v.", i) - } - - // Wrong item index should make it fail - proof.Index += 1 - { - ok = proof.Verify(itemHash, rootHash) - if ok { - t.Errorf("Expected verification to fail for wrong index %v.", i) - } - } - proof.Index -= 1 - - // Trail too long should make it fail - origInnerHashes := proof.InnerHashes - proof.InnerHashes = append(proof.InnerHashes, RandBytes(32)) - { - ok = proof.Verify(itemHash, rootHash) - if ok { - t.Errorf("Expected verification to fail for wrong trail length.") - } - } - proof.InnerHashes = origInnerHashes - - // Trail too short should make it fail - proof.InnerHashes = proof.InnerHashes[0 : len(proof.InnerHashes)-1] - { - ok = proof.Verify(itemHash, rootHash) - if ok { - t.Errorf("Expected verification to fail for wrong trail length.") - } - } - proof.InnerHashes = origInnerHashes - - // Mutating the itemHash should make it fail. - ok = proof.Verify(MutateByteSlice(itemHash), rootHash) - if ok { - t.Errorf("Expected verification to fail for mutated leaf hash") - } - - // Mutating the rootHash should make it fail. - ok = proof.Verify(itemHash, MutateByteSlice(rootHash)) - if ok { - t.Errorf("Expected verification to fail for mutated root hash") - } - } -} - -func TestKVPairs(t *testing.T) { - // NOTE: in alphabetical order for convenience. - m := map[string]interface{}{} - m["bytez"] = []byte("hizz") // 0 - m["light"] = "shadow" // 1 - m["one"] = 1 // 2 - m["one_u64"] = uint64(1) // 3 - m["struct"] = struct { // 4 - A int - B int - }{0, 1} - - kvPairsH := MakeSortedKVPairs(m) - // rootHash := SimpleHashFromHashables(kvPairsH) - proofs := SimpleProofsFromHashables(kvPairsH) - - // Some manual tests - if !bytes.Equal(proofs[1].LeafHash, KVPair{"light", "shadow"}.Hash()) { - t.Errorf("\"light\": proof failed") - fmt.Printf("%v\n%X", proofs[0], KVPair{"light", "shadow"}.Hash()) - } - if !bytes.Equal(proofs[2].LeafHash, KVPair{"one", 1}.Hash()) { - t.Errorf("\"one\": proof failed") - } - if !bytes.Equal(proofs[4].LeafHash, KVPair{"struct", struct { - A int - B int - }{0, 1}}.Hash()) { - t.Errorf("\"struct\": proof failed") - } - -} diff --git a/merkle/types.go b/merkle/types.go deleted file mode 100644 index 87f716c7..00000000 --- a/merkle/types.go +++ /dev/null @@ -1,21 +0,0 @@ -package merkle - -type Tree interface { - Size() (size int) - Height() (height int8) - Has(key interface{}) (has bool) - Get(key interface{}) (index int, value interface{}) - GetByIndex(index int) (key interface{}, value interface{}) - Set(key interface{}, value interface{}) (updated bool) - Remove(key interface{}) (value interface{}, removed bool) - HashWithCount() (hash []byte, count int) - Hash() (hash []byte) - Save() (hash []byte) - Load(hash []byte) - Copy() Tree - Iterate(func(key interface{}, value interface{}) (stop bool)) (stopped bool) -} - -type Hashable interface { - Hash() []byte -} diff --git a/merkle/util.go b/merkle/util.go deleted file mode 100644 index 89fd2741..00000000 --- a/merkle/util.go +++ /dev/null @@ -1,43 +0,0 @@ -package merkle - -import ( - "fmt" -) - -// Prints the in-memory children recursively. -func PrintIAVLNode(node *IAVLNode) { - fmt.Println("==== NODE") - if node != nil { - printIAVLNode(node, 0) - } - fmt.Println("==== END") -} - -func printIAVLNode(node *IAVLNode, indent int) { - indentPrefix := "" - for i := 0; i < indent; i++ { - indentPrefix += " " - } - - if node.rightNode != nil { - printIAVLNode(node.rightNode, indent+1) - } else if node.rightHash != nil { - fmt.Printf("%s %X\n", indentPrefix, node.rightHash) - } - - fmt.Printf("%s%v:%v\n", indentPrefix, node.key, node.height) - - if node.leftNode != nil { - printIAVLNode(node.leftNode, indent+1) - } else if node.leftHash != nil { - fmt.Printf("%s %X\n", indentPrefix, node.leftHash) - } - -} - -func maxInt8(a, b int8) int8 { - if a > b { - return a - } - return b -} diff --git a/node/config.go b/node/config.go index f78e7577..1e9d0012 100644 --- a/node/config.go +++ b/node/config.go @@ -1,7 +1,8 @@ + package node import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/node/log.go b/node/log.go index 65e5e78f..36b45149 100644 --- a/node/log.go +++ b/node/log.go @@ -1,7 +1,7 @@ package node import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "node") diff --git a/node/node.go b/node/node.go index 75c35da2..d0212a9f 100644 --- a/node/node.go +++ b/node/node.go @@ -12,12 +12,12 @@ import ( acm "github.com/tendermint/tendermint/account" bc "github.com/tendermint/tendermint/blockchain" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/consensus" - dbm "github.com/tendermint/tendermint/db" + dbm "github.com/tendermint/go-db" "github.com/tendermint/tendermint/events" mempl "github.com/tendermint/tendermint/mempool" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" "github.com/tendermint/tendermint/rpc" "github.com/tendermint/tendermint/rpc/core" "github.com/tendermint/tendermint/rpc/server" @@ -25,7 +25,7 @@ import ( stypes "github.com/tendermint/tendermint/state/types" "github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/vm" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) import _ "net/http/pprof" diff --git a/node/node_test.go b/node/node_test.go index a958c96c..38f81d5b 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -5,7 +5,7 @@ import ( "time" _ "github.com/tendermint/tendermint/config/tendermint_test" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" ) func TestNodeStartStop(t *testing.T) { diff --git a/p2p/README.md b/p2p/README.md deleted file mode 100644 index 6149d9c0..00000000 --- a/p2p/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# `tendermint/p2p` - -`tendermint/p2p` provides an abstraction around peer-to-peer communication.
- -## Peer/MConnection/Channel - -Each peer has one `MConnection` (multiplex connection) instance. - -__multiplex__ *noun* a system or signal involving simultaneous transmission of -several messages along a single channel of communication. - -Each `MConnection` handles message transmission on multiple abstract communication -`Channel`s. Each channel has a globally unique byte id. -The byte id and the relative priorities of each `Channel` are configured upon -initialization of the connection. - -There are two methods for sending messages: -```go -func (m MConnection) Send(chID byte, msg interface{}) bool {} -func (m MConnection) TrySend(chID byte, msg interface{}) bool {} -``` - -`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued -for the channel with the given id byte `chID`. The message `msg` is serialized -using the `tendermint/wire` submodule's `WriteBinary()` reflection routine. - -`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's -queue is full. - -`Send()` and `TrySend()` are also exposed for each `Peer`. - -## Switch/Reactor - -The `Switch` handles peer connections and exposes an API to receive incoming messages -on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one -or more `Channels`. So while sending outgoing messages is typically performed on the peer, -incoming messages are received on the reactor. - -```go -// Declare a MyReactor reactor that handles messages on MyChannelID. -type MyReactor struct{} - -func (reactor MyReactor) GetChannels() []*ChannelDescriptor { - return []*ChannelDescriptor{ChannelDescriptor{ID:MyChannelID, Priority: 1}} -} - -func (reactor MyReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { - r, n, err := bytes.NewBuffer(msgBytes), new(int64), new(error) - msgString := ReadString(r, n, err) - fmt.Println(msgString) -} - -// Other Reactor methods omitted for brevity -... - -switch := NewSwitch([]Reactor{MyReactor{}}) - -... - -// Send a random message to all outbound connections -for _, peer := range switch.Peers().List() { - if peer.IsOutbound() { - peer.Send(MyChannelID, "Here's a random message") - } -} -``` - -### PexReactor/AddrBook - -A `PEXReactor` reactor implementation is provided to automate peer discovery. - -```go -book := p2p.NewAddrBook(config.App.GetString("AddrBookFile")) -pexReactor := p2p.NewPEXReactor(book) -... -switch := NewSwitch([]Reactor{pexReactor, myReactor, ...}) -``` diff --git a/p2p/addrbook.go b/p2p/addrbook.go deleted file mode 100644 index 9e244751..00000000 --- a/p2p/addrbook.go +++ /dev/null @@ -1,813 +0,0 @@ -// Modified for Tendermint -// Originally Copyright (c) 2013-2014 Conformal Systems LLC. -// https://github.com/conformal/btcd/blob/master/LICENSE - -package p2p - -import ( - "encoding/binary" - "encoding/json" - "math" - "math/rand" - "net" - "os" - "sync" - "time" - - . "github.com/tendermint/tendermint/common" -) - -const ( - // addresses under which the address manager will claim to need more addresses. - needAddressThreshold = 1000 - - // interval used to dump the address cache to disk for future use. - dumpAddressInterval = time.Minute * 2 - - // max addresses in each old address bucket. - oldBucketSize = 64 - - // buckets we split old addresses over. - oldBucketCount = 64 - - // max addresses in each new address bucket. - newBucketSize = 64 - - // buckets that we spread new addresses over. - newBucketCount = 256 - - // old buckets over which an address group will be spread. - oldBucketsPerGroup = 4 - - // new buckets over which an source address group will be spread. - newBucketsPerGroup = 32 - - // buckets a frequently seen new address may end up in. - maxNewBucketsPerAddress = 4 - - // days before which we assume an address has vanished - // if we have not seen it announced in that long. - numMissingDays = 30 - - // tries without a single success before we assume an address is bad. - numRetries = 3 - - // max failures we will accept without a success before considering an address bad. - maxFailures = 10 - - // days since the last success before we will consider evicting an address. - minBadDays = 7 - - // % of total addresses known returned by GetSelection. - getSelectionPercent = 23 - - // min addresses that must be returned by GetSelection. Useful for bootstrapping. - minGetSelection = 32 - - // max addresses returned by GetSelection - maxGetSelection = 2500 - - // current version of the on-disk format. - serializationVersion = 1 -) - -/* AddrBook - concurrency safe peer address manager */ -type AddrBook struct { - QuitService - - mtx sync.Mutex - filePath string - rand *rand.Rand - key string - ourAddrs map[string]*NetAddress - addrLookup map[string]*knownAddress // new & old - addrNew []map[string]*knownAddress - addrOld []map[string]*knownAddress - wg sync.WaitGroup - nOld int - nNew int -} - -const ( - bucketTypeNew = 0x01 - bucketTypeOld = 0x02 -) - -// Use Start to begin processing asynchronous address updates. -func NewAddrBook(filePath string) *AddrBook { - am := &AddrBook{ - rand: rand.New(rand.NewSource(time.Now().UnixNano())), - ourAddrs: make(map[string]*NetAddress), - addrLookup: make(map[string]*knownAddress), - filePath: filePath, - } - am.init() - am.QuitService = *NewQuitService(log, "AddrBook", am) - return am -} - -// When modifying this, don't forget to update loadFromFile() -func (a *AddrBook) init() { - a.key = CRandHex(24) // 24/2 * 8 = 96 bits - // New addr buckets - a.addrNew = make([]map[string]*knownAddress, newBucketCount) - for i := range a.addrNew { - a.addrNew[i] = make(map[string]*knownAddress) - } - // Old addr buckets - a.addrOld = make([]map[string]*knownAddress, oldBucketCount) - for i := range a.addrOld { - a.addrOld[i] = make(map[string]*knownAddress) - } -} - -func (a *AddrBook) OnStart() error { - a.QuitService.OnStart() - a.loadFromFile(a.filePath) - a.wg.Add(1) - go a.saveRoutine() - return nil -} - -func (a *AddrBook) OnStop() { - a.QuitService.OnStop() - a.wg.Wait() -} - -func (a *AddrBook) AddOurAddress(addr *NetAddress) { - a.mtx.Lock() - defer a.mtx.Unlock() - log.Info("Add our address to book", "addr", addr) - a.ourAddrs[addr.String()] = addr -} - -func (a *AddrBook) OurAddresses() []*NetAddress { - addrs := []*NetAddress{} - for _, addr := range a.ourAddrs { - addrs = append(addrs, addr) - } - return addrs -} - -func (a *AddrBook) AddAddress(addr *NetAddress, src *NetAddress) { - a.mtx.Lock() - defer a.mtx.Unlock() - log.Info("Add address to book", "addr", addr, "src", src) - a.addAddress(addr, src) -} - -func (a *AddrBook) NeedMoreAddrs() bool { - return a.Size() < needAddressThreshold -} - -func (a *AddrBook) Size() int { - a.mtx.Lock() - defer a.mtx.Unlock() - return a.size() -} - -func (a *AddrBook) size() int { - return a.nNew + a.nOld -} - -// Pick an address to connect to with new/old bias. -func (a *AddrBook) PickAddress(newBias int) *NetAddress { - a.mtx.Lock() - defer a.mtx.Unlock() - - if a.size() == 0 { - return nil - } - if newBias > 100 { - newBias = 100 - } - if newBias < 0 { - newBias = 0 - } - - // Bias between new and old addresses. - oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(newBias)) - newCorrelation := math.Sqrt(float64(a.nNew)) * float64(newBias) - - if (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation { - // pick random Old bucket. - var bucket map[string]*knownAddress = nil - for len(bucket) == 0 { - bucket = a.addrOld[a.rand.Intn(len(a.addrOld))] - } - // pick a random ka from bucket. - randIndex := a.rand.Intn(len(bucket)) - for _, ka := range bucket { - if randIndex == 0 { - return ka.Addr - } - randIndex-- - } - PanicSanity("Should not happen") - } else { - // pick random New bucket. - var bucket map[string]*knownAddress = nil - for len(bucket) == 0 { - bucket = a.addrNew[a.rand.Intn(len(a.addrNew))] - } - // pick a random ka from bucket. - randIndex := a.rand.Intn(len(bucket)) - for _, ka := range bucket { - if randIndex == 0 { - return ka.Addr - } - randIndex-- - } - PanicSanity("Should not happen") - } - return nil -} - -func (a *AddrBook) MarkGood(addr *NetAddress) { - a.mtx.Lock() - defer a.mtx.Unlock() - ka := a.addrLookup[addr.String()] - if ka == nil { - return - } - ka.markGood() - if ka.isNew() { - a.moveToOld(ka) - } -} - -func (a *AddrBook) MarkAttempt(addr *NetAddress) { - a.mtx.Lock() - defer a.mtx.Unlock() - ka := a.addrLookup[addr.String()] - if ka == nil { - return - } - ka.markAttempt() -} - -func (a *AddrBook) MarkBad(addr *NetAddress) { - a.mtx.Lock() - defer a.mtx.Unlock() - ka := a.addrLookup[addr.String()] - if ka == nil { - return - } - // We currently just eject the address. - // In the future, consider blacklisting. - a.removeFromAllBuckets(ka) -} - -/* Peer exchange */ - -// GetSelection randomly selects some addresses (old & new). Suitable for peer-exchange protocols. -func (a *AddrBook) GetSelection() []*NetAddress { - a.mtx.Lock() - defer a.mtx.Unlock() - - if a.size() == 0 { - return nil - } - - allAddr := make([]*NetAddress, a.size()) - i := 0 - for _, v := range a.addrLookup { - allAddr[i] = v.Addr - i++ - } - - numAddresses := MaxInt( - MinInt(minGetSelection, len(allAddr)), - len(allAddr)*getSelectionPercent/100) - numAddresses = MinInt(maxGetSelection, numAddresses) - - // Fisher-Yates shuffle the array. We only need to do the first - // `numAddresses' since we are throwing the rest. - for i := 0; i < numAddresses; i++ { - // pick a number between current index and the end - j := rand.Intn(len(allAddr)-i) + i - allAddr[i], allAddr[j] = allAddr[j], allAddr[i] - } - - // slice off the limit we are willing to share. - return allAddr[:numAddresses] -} - -/* Loading & Saving */ - -type addrBookJSON struct { - Key string - Addrs []*knownAddress -} - -func (a *AddrBook) saveToFile(filePath string) { - // Compile Addrs - addrs := []*knownAddress{} - for _, ka := range a.addrLookup { - addrs = append(addrs, ka) - } - - aJSON := &addrBookJSON{ - Key: a.key, - Addrs: addrs, - } - - jsonBytes, err := json.MarshalIndent(aJSON, "", "\t") - if err != nil { - log.Error("Failed to save AddrBook to file", "err", err) - return - } - err = WriteFileAtomic(filePath, jsonBytes) - if err != nil { - log.Error("Failed to save AddrBook to file", "file", filePath, "error", err) - } -} - -// Returns false if file does not exist. -// Panics if file is corrupt. -func (a *AddrBook) loadFromFile(filePath string) bool { - // If doesn't exist, do nothing. - _, err := os.Stat(filePath) - if os.IsNotExist(err) { - return false - } - - // Load addrBookJSON{} - r, err := os.Open(filePath) - if err != nil { - PanicCrisis(Fmt("Error opening file %s: %v", filePath, err)) - } - defer r.Close() - aJSON := &addrBookJSON{} - dec := json.NewDecoder(r) - err = dec.Decode(aJSON) - if err != nil { - PanicCrisis(Fmt("Error reading file %s: %v", filePath, err)) - } - - // Restore all the fields... - // Restore the key - a.key = aJSON.Key - // Restore .addrNew & .addrOld - for _, ka := range aJSON.Addrs { - for _, bucketIndex := range ka.Buckets { - bucket := a.getBucket(ka.BucketType, bucketIndex) - bucket[ka.Addr.String()] = ka - } - a.addrLookup[ka.Addr.String()] = ka - if ka.BucketType == bucketTypeNew { - a.nNew++ - } else { - a.nOld++ - } - } - return true -} - -/* Private methods */ - -func (a *AddrBook) saveRoutine() { - dumpAddressTicker := time.NewTicker(dumpAddressInterval) -out: - for { - select { - case <-dumpAddressTicker.C: - log.Info("Saving AddrBook to file", "size", a.Size()) - a.saveToFile(a.filePath) - case <-a.Quit: - break out - } - } - dumpAddressTicker.Stop() - a.saveToFile(a.filePath) - a.wg.Done() - log.Notice("Address handler done") -} - -func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress { - switch bucketType { - case bucketTypeNew: - return a.addrNew[bucketIdx] - case bucketTypeOld: - return a.addrOld[bucketIdx] - default: - PanicSanity("Should not happen") - return nil - } -} - -// Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full. -// NOTE: currently it always returns true. -func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool { - // Sanity check - if ka.isOld() { - log.Warn(Fmt("Cannot add address already in old bucket to a new bucket: %v", ka)) - return false - } - - addrStr := ka.Addr.String() - bucket := a.getBucket(bucketTypeNew, bucketIdx) - - // Already exists? - if _, ok := bucket[addrStr]; ok { - return true - } - - // Enforce max addresses. - if len(bucket) > newBucketSize { - log.Notice("new bucket is full, expiring old ") - a.expireNew(bucketIdx) - } - - // Add to bucket. - bucket[addrStr] = ka - if ka.addBucketRef(bucketIdx) == 1 { - a.nNew++ - } - - // Ensure in addrLookup - a.addrLookup[addrStr] = ka - - return true -} - -// Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full. -func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { - // Sanity check - if ka.isNew() { - log.Warn(Fmt("Cannot add new address to old bucket: %v", ka)) - return false - } - if len(ka.Buckets) != 0 { - log.Warn(Fmt("Cannot add already old address to another old bucket: %v", ka)) - return false - } - - addrStr := ka.Addr.String() - bucket := a.getBucket(bucketTypeNew, bucketIdx) - - // Already exists? - if _, ok := bucket[addrStr]; ok { - return true - } - - // Enforce max addresses. - if len(bucket) > oldBucketSize { - return false - } - - // Add to bucket. - bucket[addrStr] = ka - if ka.addBucketRef(bucketIdx) == 1 { - a.nOld++ - } - - // Ensure in addrLookup - a.addrLookup[addrStr] = ka - - return true -} - -func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) { - if ka.BucketType != bucketType { - log.Warn(Fmt("Bucket type mismatch: %v", ka)) - return - } - bucket := a.getBucket(bucketType, bucketIdx) - delete(bucket, ka.Addr.String()) - if ka.removeBucketRef(bucketIdx) == 0 { - if bucketType == bucketTypeNew { - a.nNew-- - } else { - a.nOld-- - } - delete(a.addrLookup, ka.Addr.String()) - } -} - -func (a *AddrBook) removeFromAllBuckets(ka *knownAddress) { - for _, bucketIdx := range ka.Buckets { - bucket := a.getBucket(ka.BucketType, bucketIdx) - delete(bucket, ka.Addr.String()) - } - ka.Buckets = nil - if ka.BucketType == bucketTypeNew { - a.nNew-- - } else { - a.nOld-- - } - delete(a.addrLookup, ka.Addr.String()) -} - -func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { - bucket := a.getBucket(bucketType, bucketIdx) - var oldest *knownAddress - for _, ka := range bucket { - if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) { - oldest = ka - } - } - return oldest -} - -func (a *AddrBook) addAddress(addr, src *NetAddress) { - if !addr.Routable() { - log.Warn(Fmt("Cannot add non-routable address %v", addr)) - return - } - if _, ok := a.ourAddrs[addr.String()]; ok { - // Ignore our own listener address. - return - } - - ka := a.addrLookup[addr.String()] - - if ka != nil { - // Already old. - if ka.isOld() { - return - } - // Already in max new buckets. - if len(ka.Buckets) == maxNewBucketsPerAddress { - return - } - // The more entries we have, the less likely we are to add more. - factor := int32(2 * len(ka.Buckets)) - if a.rand.Int31n(factor) != 0 { - return - } - } else { - ka = newKnownAddress(addr, src) - } - - bucket := a.calcNewBucket(addr, src) - a.addToNewBucket(ka, bucket) - - log.Notice("Added new address", "address", addr, "total", a.size()) -} - -// Make space in the new buckets by expiring the really bad entries. -// If no bad entries are available we remove the oldest. -func (a *AddrBook) expireNew(bucketIdx int) { - for addrStr, ka := range a.addrNew[bucketIdx] { - // If an entry is bad, throw it away - if ka.isBad() { - log.Notice(Fmt("expiring bad address %v", addrStr)) - a.removeFromBucket(ka, bucketTypeNew, bucketIdx) - return - } - } - - // If we haven't thrown out a bad entry, throw out the oldest entry - oldest := a.pickOldest(bucketTypeNew, bucketIdx) - a.removeFromBucket(oldest, bucketTypeNew, bucketIdx) -} - -// Promotes an address from new to old. -// TODO: Move to old probabilistically. -// The better a node is, the less likely it should be evicted from an old bucket. -func (a *AddrBook) moveToOld(ka *knownAddress) { - // Sanity check - if ka.isOld() { - log.Warn(Fmt("Cannot promote address that is already old %v", ka)) - return - } - if len(ka.Buckets) == 0 { - log.Warn(Fmt("Cannot promote address that isn't in any new buckets %v", ka)) - return - } - - // Remember one of the buckets in which ka is in. - freedBucket := ka.Buckets[0] - // Remove from all (new) buckets. - a.removeFromAllBuckets(ka) - // It's officially old now. - ka.BucketType = bucketTypeOld - - // Try to add it to its oldBucket destination. - oldBucketIdx := a.calcOldBucket(ka.Addr) - added := a.addToOldBucket(ka, oldBucketIdx) - if !added { - // No room, must evict something - oldest := a.pickOldest(bucketTypeOld, oldBucketIdx) - a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx) - // Find new bucket to put oldest in - newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src) - added := a.addToNewBucket(oldest, newBucketIdx) - // No space in newBucket either, just put it in freedBucket from above. - if !added { - added := a.addToNewBucket(oldest, freedBucket) - if !added { - log.Warn(Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket)) - } - } - // Finally, add to bucket again. - added = a.addToOldBucket(ka, oldBucketIdx) - if !added { - log.Warn(Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) - } - } -} - -// doublesha256( key + sourcegroup + -// int64(doublesha256(key + group + sourcegroup))%bucket_per_group ) % num_new_buckets -func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int { - data1 := []byte{} - data1 = append(data1, []byte(a.key)...) - data1 = append(data1, []byte(groupKey(addr))...) - data1 = append(data1, []byte(groupKey(src))...) - hash1 := doubleSha256(data1) - hash64 := binary.BigEndian.Uint64(hash1) - hash64 %= newBucketsPerGroup - var hashbuf [8]byte - binary.BigEndian.PutUint64(hashbuf[:], hash64) - data2 := []byte{} - data2 = append(data2, []byte(a.key)...) - data2 = append(data2, groupKey(src)...) - data2 = append(data2, hashbuf[:]...) - - hash2 := doubleSha256(data2) - return int(binary.BigEndian.Uint64(hash2) % newBucketCount) -} - -// doublesha256( key + group + -// int64(doublesha256(key + addr))%buckets_per_group ) % num_old_buckets -func (a *AddrBook) calcOldBucket(addr *NetAddress) int { - data1 := []byte{} - data1 = append(data1, []byte(a.key)...) - data1 = append(data1, []byte(addr.String())...) - hash1 := doubleSha256(data1) - hash64 := binary.BigEndian.Uint64(hash1) - hash64 %= oldBucketsPerGroup - var hashbuf [8]byte - binary.BigEndian.PutUint64(hashbuf[:], hash64) - data2 := []byte{} - data2 = append(data2, []byte(a.key)...) - data2 = append(data2, groupKey(addr)...) - data2 = append(data2, hashbuf[:]...) - - hash2 := doubleSha256(data2) - return int(binary.BigEndian.Uint64(hash2) % oldBucketCount) -} - -// Return a string representing the network group of this address. -// This is the /16 for IPv6, the /32 (/36 for he.net) for IPv6, the string -// "local" for a local address and the string "unroutable for an unroutable -// address. -func groupKey(na *NetAddress) string { - if na.Local() { - return "local" - } - if !na.Routable() { - return "unroutable" - } - - if ipv4 := na.IP.To4(); ipv4 != nil { - return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String() - } - if na.RFC6145() || na.RFC6052() { - // last four bytes are the ip address - ip := net.IP(na.IP[12:16]) - return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String() - } - - if na.RFC3964() { - ip := net.IP(na.IP[2:7]) - return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String() - - } - if na.RFC4380() { - // teredo tunnels have the last 4 bytes as the v4 address XOR - // 0xff. - ip := net.IP(make([]byte, 4)) - for i, byte := range na.IP[12:16] { - ip[i] = byte ^ 0xff - } - return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String() - } - - // OK, so now we know ourselves to be a IPv6 address. - // bitcoind uses /32 for everything, except for Hurricane Electric's - // (he.net) IP range, which it uses /36 for. - bits := 32 - heNet := &net.IPNet{IP: net.ParseIP("2001:470::"), - Mask: net.CIDRMask(32, 128)} - if heNet.Contains(na.IP) { - bits = 36 - } - - return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String() -} - -//----------------------------------------------------------------------------- - -/* - knownAddress - - tracks information about a known network address that is used - to determine how viable an address is. -*/ -type knownAddress struct { - Addr *NetAddress - Src *NetAddress - Attempts int32 - LastAttempt time.Time - LastSuccess time.Time - BucketType byte - Buckets []int -} - -func newKnownAddress(addr *NetAddress, src *NetAddress) *knownAddress { - return &knownAddress{ - Addr: addr, - Src: src, - Attempts: 0, - LastAttempt: time.Now(), - BucketType: bucketTypeNew, - Buckets: nil, - } -} - -func (ka *knownAddress) isOld() bool { - return ka.BucketType == bucketTypeOld -} - -func (ka *knownAddress) isNew() bool { - return ka.BucketType == bucketTypeNew -} - -func (ka *knownAddress) markAttempt() { - now := time.Now() - ka.LastAttempt = now - ka.Attempts += 1 -} - -func (ka *knownAddress) markGood() { - now := time.Now() - ka.LastAttempt = now - ka.Attempts = 0 - ka.LastSuccess = now -} - -func (ka *knownAddress) addBucketRef(bucketIdx int) int { - for _, bucket := range ka.Buckets { - if bucket == bucketIdx { - log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka)) - return -1 - } - } - ka.Buckets = append(ka.Buckets, bucketIdx) - return len(ka.Buckets) -} - -func (ka *knownAddress) removeBucketRef(bucketIdx int) int { - buckets := []int{} - for _, bucket := range ka.Buckets { - if bucket != bucketIdx { - buckets = append(buckets, bucket) - } - } - if len(buckets) != len(ka.Buckets)-1 { - log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka)) - return -1 - } - ka.Buckets = buckets - return len(ka.Buckets) -} - -/* - An address is bad if the address in question has not been tried in the last - minute and meets one of the following criteria: - - 1) It claims to be from the future - 2) It hasn't been seen in over a month - 3) It has failed at least three times and never succeeded - 4) It has failed ten times in the last week - - All addresses that meet these criteria are assumed to be worthless and not - worth keeping hold of. -*/ -func (ka *knownAddress) isBad() bool { - // Has been attempted in the last minute --> good - if ka.LastAttempt.Before(time.Now().Add(-1 * time.Minute)) { - return false - } - - // Over a month old? - if ka.LastAttempt.After(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) { - return true - } - - // Never succeeded? - if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries { - return true - } - - // Hasn't succeeded in too long? - if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) && - ka.Attempts >= maxFailures { - return true - } - - return false -} diff --git a/p2p/addrbook_test.go b/p2p/addrbook_test.go deleted file mode 100644 index 50986452..00000000 --- a/p2p/addrbook_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package p2p - -import ( - "fmt" - "io/ioutil" - "math/rand" - "testing" -) - -func createTempFileName(prefix string) string { - f, err := ioutil.TempFile("", prefix) - if err != nil { - panic(err) - } - fname := f.Name() - err = f.Close() - if err != nil { - panic(err) - } - return fname -} - -func TestEmpty(t *testing.T) { - fname := createTempFileName("addrbook_test") - // t.Logf("New tempfile name: %v", fname) - - // Save an empty book & load it - book := NewAddrBook(fname) - book.saveToFile(fname) - - book = NewAddrBook(fname) - book.loadFromFile(fname) - - if book.Size() != 0 { - t.Errorf("Expected 0 addresses, found %v", book.Size()) - } -} - -func randIPv4Address() *NetAddress { - for { - ip := fmt.Sprintf("%v.%v.%v.%v", - rand.Intn(254)+1, - rand.Intn(255), - rand.Intn(255), - rand.Intn(255), - ) - port := rand.Intn(65535-1) + 1 - addr := NewNetAddressString(fmt.Sprintf("%v:%v", ip, port)) - if addr.Routable() { - return addr - } - } -} - -func TestSaveAddresses(t *testing.T) { - fname := createTempFileName("addrbook_test") - //t.Logf("New tempfile name: %v", fname) - - // Create some random addresses - randAddrs := []struct { - addr *NetAddress - src *NetAddress - }{} - for i := 0; i < 100; i++ { - addr := randIPv4Address() - src := randIPv4Address() - randAddrs = append(randAddrs, struct { - addr *NetAddress - src *NetAddress - }{ - addr: addr, - src: src, - }) - } - - // Create the book & populate & save - book := NewAddrBook(fname) - for _, addrSrc := range randAddrs { - book.AddAddress(addrSrc.addr, addrSrc.src) - } - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", book.Size()) - } - book.saveToFile(fname) - - // Reload the book - book = NewAddrBook(fname) - book.loadFromFile(fname) - - // Test ... - - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", book.Size()) - } - - for _, addrSrc := range randAddrs { - addr := addrSrc.addr - src := addrSrc.src - ka := book.addrLookup[addr.String()] - if ka == nil { - t.Fatalf("Expected to find KnownAddress %v but wasn't there.", addr) - } - if !(ka.Addr.Equals(addr) && ka.Src.Equals(src)) { - t.Fatalf("KnownAddress doesn't match addr & src") - } - } -} - -func TestPromoteToOld(t *testing.T) { - fname := createTempFileName("addrbook_test") - t.Logf("New tempfile name: %v", fname) - - // Create some random addresses - randAddrs := []struct { - addr *NetAddress - src *NetAddress - }{} - for i := 0; i < 100; i++ { - addr := randIPv4Address() - src := randIPv4Address() - randAddrs = append(randAddrs, struct { - addr *NetAddress - src *NetAddress - }{ - addr: addr, - src: src, - }) - } - - // Create the book & populate & save - book := NewAddrBook(fname) - for _, addrSrc := range randAddrs { - book.AddAddress(addrSrc.addr, addrSrc.src) - } - // Attempt all addresses. - for _, addrSrc := range randAddrs { - book.MarkAttempt(addrSrc.addr) - } - // Promote half of them - for i, addrSrc := range randAddrs { - if i%2 == 0 { - book.MarkGood(addrSrc.addr) - } - } - book.saveToFile(fname) - - // Reload the book - book = NewAddrBook(fname) - book.loadFromFile(fname) - - // Test ... - - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", book.Size()) - } - - // TODO: do more testing :) - - selection := book.GetSelection() - t.Logf("selection: %v", selection) -} diff --git a/p2p/config.go b/p2p/config.go deleted file mode 100644 index c9cbf126..00000000 --- a/p2p/config.go +++ /dev/null @@ -1,13 +0,0 @@ -package p2p - -import ( - cfg "github.com/tendermint/tendermint/config" -) - -var config cfg.Config = nil - -func init() { - cfg.OnConfig(func(newConfig cfg.Config) { - config = newConfig - }) -} diff --git a/p2p/connection.go b/p2p/connection.go deleted file mode 100644 index a9060467..00000000 --- a/p2p/connection.go +++ /dev/null @@ -1,640 +0,0 @@ -package p2p - -import ( - "bufio" - "fmt" - "io" - "math" - "net" - "runtime/debug" - "sync/atomic" - "time" - - flow "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" //"github.com/tendermint/log15" -) - -const ( - numBatchMsgPackets = 10 - minReadBufferSize = 1024 - minWriteBufferSize = 1024 - idleTimeoutMinutes = 5 - updateStatsSeconds = 2 - pingTimeoutSeconds = 40 - defaultSendRate = 51200 // 50Kb/s - defaultRecvRate = 51200 // 50Kb/s - flushThrottleMS = 100 - defaultSendQueueCapacity = 1 - defaultRecvBufferCapacity = 4096 - defaultSendTimeoutSeconds = 10 -) - -type receiveCbFunc func(chID byte, msgBytes []byte) -type errorCbFunc func(interface{}) - -/* -Each peer has one `MConnection` (multiplex connection) instance. - -__multiplex__ *noun* a system or signal involving simultaneous transmission of -several messages along a single channel of communication. - -Each `MConnection` handles message transmission on multiple abstract communication -`Channel`s. Each channel has a globally unique byte id. -The byte id and the relative priorities of each `Channel` are configured upon -initialization of the connection. - -There are two methods for sending messages: - func (m MConnection) Send(chID byte, msg interface{}) bool {} - func (m MConnection) TrySend(chID byte, msg interface{}) bool {} - -`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued -for the channel with the given id byte `chID`, or until the request times out. -The message `msg` is serialized using the `tendermint/wire` submodule's -`WriteBinary()` reflection routine. - -`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's -queue is full. - -Inbound message bytes are handled with an onReceive callback function. -*/ -type MConnection struct { - BaseService - - conn net.Conn - bufReader *bufio.Reader - bufWriter *bufio.Writer - sendMonitor *flow.Monitor - recvMonitor *flow.Monitor - sendRate int64 - recvRate int64 - send chan struct{} - pong chan struct{} - channels []*Channel - channelsIdx map[byte]*Channel - onReceive receiveCbFunc - onError errorCbFunc - errored uint32 - - quit chan struct{} - flushTimer *ThrottleTimer // flush writes as necessary but throttled. - pingTimer *RepeatTimer // send pings periodically - chStatsTimer *RepeatTimer // update channel stats periodically - - LocalAddress *NetAddress - RemoteAddress *NetAddress -} - -func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { - - mconn := &MConnection{ - conn: conn, - bufReader: bufio.NewReaderSize(conn, minReadBufferSize), - bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize), - sendMonitor: flow.New(0, 0), - recvMonitor: flow.New(0, 0), - sendRate: defaultSendRate, - recvRate: defaultRecvRate, - send: make(chan struct{}, 1), - pong: make(chan struct{}), - onReceive: onReceive, - onError: onError, - - // Initialized in Start() - quit: nil, - flushTimer: nil, - pingTimer: nil, - chStatsTimer: nil, - - LocalAddress: NewNetAddress(conn.LocalAddr()), - RemoteAddress: NewNetAddress(conn.RemoteAddr()), - } - - // Create channels - var channelsIdx = map[byte]*Channel{} - var channels = []*Channel{} - - for _, desc := range chDescs { - channel := newChannel(mconn, desc) - channelsIdx[channel.id] = channel - channels = append(channels, channel) - } - mconn.channels = channels - mconn.channelsIdx = channelsIdx - - mconn.BaseService = *NewBaseService(log, "MConnection", mconn) - - return mconn -} - -func (c *MConnection) OnStart() error { - c.BaseService.OnStart() - c.quit = make(chan struct{}) - c.flushTimer = NewThrottleTimer("flush", flushThrottleMS*time.Millisecond) - c.pingTimer = NewRepeatTimer("ping", pingTimeoutSeconds*time.Second) - c.chStatsTimer = NewRepeatTimer("chStats", updateStatsSeconds*time.Second) - go c.sendRoutine() - go c.recvRoutine() - return nil -} - -func (c *MConnection) OnStop() { - c.BaseService.OnStop() - c.flushTimer.Stop() - c.pingTimer.Stop() - c.chStatsTimer.Stop() - if c.quit != nil { - close(c.quit) - } - c.conn.Close() - // We can't close pong safely here because - // recvRoutine may write to it after we've stopped. - // Though it doesn't need to get closed at all, - // we close it @ recvRoutine. - // close(c.pong) -} - -func (c *MConnection) String() string { - return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr()) -} - -func (c *MConnection) flush() { - log.Debug("Flush", "conn", c) - err := c.bufWriter.Flush() - if err != nil { - log.Warn("MConnection flush failed", "error", err) - } -} - -// Catch panics, usually caused by remote disconnects. -func (c *MConnection) _recover() { - if r := recover(); r != nil { - stack := debug.Stack() - err := StackError{r, stack} - c.stopForError(err) - } -} - -func (c *MConnection) stopForError(r interface{}) { - c.Stop() - if atomic.CompareAndSwapUint32(&c.errored, 0, 1) { - if c.onError != nil { - c.onError(r) - } - } -} - -// Queues a message to be sent to channel. -func (c *MConnection) Send(chID byte, msg interface{}) bool { - if !c.IsRunning() { - return false - } - - log.Info("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) - - // Send message to channel. - channel, ok := c.channelsIdx[chID] - if !ok { - log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) - return false - } - - success := channel.sendBytes(wire.BinaryBytes(msg)) - if success { - // Wake up sendRoutine if necessary - select { - case c.send <- struct{}{}: - default: - } - } else { - log.Warn("Send failed", "channel", chID, "conn", c, "msg", msg) - } - return success -} - -// Queues a message to be sent to channel. -// Nonblocking, returns true if successful. -func (c *MConnection) TrySend(chID byte, msg interface{}) bool { - if !c.IsRunning() { - return false - } - - log.Info("TrySend", "channel", chID, "conn", c, "msg", msg) - - // Send message to channel. - channel, ok := c.channelsIdx[chID] - if !ok { - log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) - return false - } - - ok = channel.trySendBytes(wire.BinaryBytes(msg)) - if ok { - // Wake up sendRoutine if necessary - select { - case c.send <- struct{}{}: - default: - } - } - - return ok -} - -func (c *MConnection) CanSend(chID byte) bool { - if !c.IsRunning() { - return false - } - - channel, ok := c.channelsIdx[chID] - if !ok { - log.Error(Fmt("Unknown channel %X", chID)) - return false - } - return channel.canSend() -} - -// sendRoutine polls for packets to send from channels. -func (c *MConnection) sendRoutine() { - defer c._recover() - -FOR_LOOP: - for { - var n int64 - var err error - select { - case <-c.flushTimer.Ch: - // NOTE: flushTimer.Set() must be called every time - // something is written to .bufWriter. - c.flush() - case <-c.chStatsTimer.Ch: - for _, channel := range c.channels { - channel.updateStats() - } - case <-c.pingTimer.Ch: - log.Info("Send Ping") - wire.WriteByte(packetTypePing, c.bufWriter, &n, &err) - c.sendMonitor.Update(int(n)) - c.flush() - case <-c.pong: - log.Info("Send Pong") - wire.WriteByte(packetTypePong, c.bufWriter, &n, &err) - c.sendMonitor.Update(int(n)) - c.flush() - case <-c.quit: - break FOR_LOOP - case <-c.send: - // Send some msgPackets - eof := c.sendSomeMsgPackets() - if !eof { - // Keep sendRoutine awake. - select { - case c.send <- struct{}{}: - default: - } - } - } - - if !c.IsRunning() { - break FOR_LOOP - } - if err != nil { - log.Warn("Connection failed @ sendRoutine", "conn", c, "error", err) - c.stopForError(err) - break FOR_LOOP - } - } - - // Cleanup -} - -// Returns true if messages from channels were exhausted. -// Blocks in accordance to .sendMonitor throttling. -func (c *MConnection) sendSomeMsgPackets() bool { - // Block until .sendMonitor says we can write. - // Once we're ready we send more than we asked for, - // but amortized it should even out. - c.sendMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.sendRate), true) - - // Now send some msgPackets. - for i := 0; i < numBatchMsgPackets; i++ { - if c.sendMsgPacket() { - return true - } - } - return false -} - -// Returns true if messages from channels were exhausted. -func (c *MConnection) sendMsgPacket() bool { - // Choose a channel to create a msgPacket from. - // The chosen channel will be the one whose recentlySent/priority is the least. - var leastRatio float32 = math.MaxFloat32 - var leastChannel *Channel - for _, channel := range c.channels { - // If nothing to send, skip this channel - if !channel.isSendPending() { - continue - } - // Get ratio, and keep track of lowest ratio. - ratio := float32(channel.recentlySent) / float32(channel.priority) - if ratio < leastRatio { - leastRatio = ratio - leastChannel = channel - } - } - - // Nothing to send? - if leastChannel == nil { - return true - } else { - // log.Info("Found a msgPacket to send") - } - - // Make & send a msgPacket from this channel - n, err := leastChannel.writeMsgPacketTo(c.bufWriter) - if err != nil { - log.Warn("Failed to write msgPacket", "error", err) - c.stopForError(err) - return true - } - c.sendMonitor.Update(int(n)) - c.flushTimer.Set() - return false -} - -// recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer. -// After a whole message has been assembled, it's pushed to onReceive(). -// Blocks depending on how the connection is throttled. -func (c *MConnection) recvRoutine() { - defer c._recover() - -FOR_LOOP: - for { - // Block until .recvMonitor says we can read. - c.recvMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.recvRate), true) - - /* - // Peek into bufReader for debugging - if numBytes := c.bufReader.Buffered(); numBytes > 0 { - log.Info("Peek connection buffer", "numBytes", numBytes, "bytes", log15.Lazy{func() []byte { - bytes, err := c.bufReader.Peek(MinInt(numBytes, 100)) - if err == nil { - return bytes - } else { - log.Warn("Error peeking connection buffer", "error", err) - return nil - } - }}) - } - */ - - // Read packet type - var n int64 - var err error - pktType := wire.ReadByte(c.bufReader, &n, &err) - c.recvMonitor.Update(int(n)) - if err != nil { - if c.IsRunning() { - log.Warn("Connection failed @ recvRoutine (reading byte)", "conn", c, "error", err) - c.stopForError(err) - } - break FOR_LOOP - } - - // Read more depending on packet type. - switch pktType { - case packetTypePing: - // TODO: prevent abuse, as they cause flush()'s. - log.Info("Receive Ping") - c.pong <- struct{}{} - case packetTypePong: - // do nothing - log.Info("Receive Pong") - case packetTypeMsg: - pkt, n, err := msgPacket{}, int64(0), error(nil) - wire.ReadBinaryPtr(&pkt, c.bufReader, &n, &err) - c.recvMonitor.Update(int(n)) - if err != nil { - if c.IsRunning() { - log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err) - c.stopForError(err) - } - break FOR_LOOP - } - channel, ok := c.channelsIdx[pkt.ChannelID] - if !ok || channel == nil { - PanicQ(Fmt("Unknown channel %X", pkt.ChannelID)) - } - msgBytes, err := channel.recvMsgPacket(pkt) - if err != nil { - if c.IsRunning() { - log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err) - c.stopForError(err) - } - break FOR_LOOP - } - if msgBytes != nil { - log.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes) - c.onReceive(pkt.ChannelID, msgBytes) - } - default: - PanicSanity(Fmt("Unknown message type %X", pktType)) - } - - // TODO: shouldn't this go in the sendRoutine? - // Better to send a ping packet when *we* haven't sent anything for a while. - c.pingTimer.Reset() - } - - // Cleanup - close(c.pong) - for _ = range c.pong { - // Drain - } -} - -//----------------------------------------------------------------------------- - -type ChannelDescriptor struct { - ID byte - Priority int - SendQueueCapacity int - RecvBufferCapacity int -} - -func (chDesc *ChannelDescriptor) FillDefaults() { - if chDesc.SendQueueCapacity == 0 { - chDesc.SendQueueCapacity = defaultSendQueueCapacity - } - if chDesc.RecvBufferCapacity == 0 { - chDesc.RecvBufferCapacity = defaultRecvBufferCapacity - } -} - -// TODO: lowercase. -// NOTE: not goroutine-safe. -type Channel struct { - conn *MConnection - desc *ChannelDescriptor - id byte - sendQueue chan []byte - sendQueueSize int32 // atomic. - recving []byte - sending []byte - priority int - recentlySent int64 // exponential moving average -} - -func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel { - desc.FillDefaults() - if desc.Priority <= 0 { - PanicSanity("Channel default priority must be a postive integer") - } - return &Channel{ - conn: conn, - desc: desc, - id: desc.ID, - sendQueue: make(chan []byte, desc.SendQueueCapacity), - recving: make([]byte, 0, desc.RecvBufferCapacity), - priority: desc.Priority, - } -} - -// Queues message to send to this channel. -// Goroutine-safe -// Times out (and returns false) after defaultSendTimeoutSeconds -func (ch *Channel) sendBytes(bytes []byte) bool { - timeout := time.NewTimer(defaultSendTimeoutSeconds * time.Second) - select { - case <-timeout.C: - // timeout - return false - case ch.sendQueue <- bytes: - atomic.AddInt32(&ch.sendQueueSize, 1) - return true - } -} - -// Queues message to send to this channel. -// Nonblocking, returns true if successful. -// Goroutine-safe -func (ch *Channel) trySendBytes(bytes []byte) bool { - select { - case ch.sendQueue <- bytes: - atomic.AddInt32(&ch.sendQueueSize, 1) - return true - default: - return false - } -} - -// Goroutine-safe -func (ch *Channel) loadSendQueueSize() (size int) { - return int(atomic.LoadInt32(&ch.sendQueueSize)) -} - -// Goroutine-safe -// Use only as a heuristic. -func (ch *Channel) canSend() bool { - return ch.loadSendQueueSize() < defaultSendQueueCapacity -} - -// Returns true if any msgPackets are pending to be sent. -// Call before calling nextMsgPacket() -// Goroutine-safe -func (ch *Channel) isSendPending() bool { - if len(ch.sending) == 0 { - if len(ch.sendQueue) == 0 { - return false - } - ch.sending = <-ch.sendQueue - } - return true -} - -// Creates a new msgPacket to send. -// Not goroutine-safe -func (ch *Channel) nextMsgPacket() msgPacket { - packet := msgPacket{} - packet.ChannelID = byte(ch.id) - packet.Bytes = ch.sending[:MinInt(maxMsgPacketSize, len(ch.sending))] - if len(ch.sending) <= maxMsgPacketSize { - packet.EOF = byte(0x01) - ch.sending = nil - atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize - } else { - packet.EOF = byte(0x00) - ch.sending = ch.sending[MinInt(maxMsgPacketSize, len(ch.sending)):] - } - return packet -} - -// Writes next msgPacket to w. -// Not goroutine-safe -func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int64, err error) { - packet := ch.nextMsgPacket() - log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet) - wire.WriteByte(packetTypeMsg, w, &n, &err) - wire.WriteBinary(packet, w, &n, &err) - if err != nil { - ch.recentlySent += n - } - return -} - -// Handles incoming msgPackets. Returns a msg bytes if msg is complete. -// Not goroutine-safe -func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { - // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet) - if wire.MaxBinaryReadSize < len(ch.recving)+len(packet.Bytes) { - return nil, wire.ErrBinaryReadSizeOverflow - } - ch.recving = append(ch.recving, packet.Bytes...) - if packet.EOF == byte(0x01) { - msgBytes := ch.recving - ch.recving = make([]byte, 0, defaultRecvBufferCapacity) - return msgBytes, nil - } - return nil, nil -} - -// Call this periodically to update stats for throttling purposes. -// Not goroutine-safe -func (ch *Channel) updateStats() { - // Exponential decay of stats. - // TODO: optimize. - ch.recentlySent = int64(float64(ch.recentlySent) * 0.5) -} - -//----------------------------------------------------------------------------- - -const ( - maxMsgPacketSize = 1024 - packetTypePing = byte(0x01) - packetTypePong = byte(0x02) - packetTypeMsg = byte(0x03) -) - -// Messages in channels are chopped into smaller msgPackets for multiplexing. -type msgPacket struct { - ChannelID byte - EOF byte // 1 means message ends here. - Bytes []byte -} - -func (p msgPacket) String() string { - return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF) -} - -//----------------------------------------------------------------------------- - -// Convenience struct for writing typed messages. -// Reading requires a custom decoder that switches on the first type byte of a byteslice. -type TypedMessage struct { - Type byte - Msg interface{} -} - -func (tm TypedMessage) String() string { - return fmt.Sprintf("TMsg{%X:%v}", tm.Type, tm.Msg) -} diff --git a/p2p/listener.go b/p2p/listener.go deleted file mode 100644 index 131d9695..00000000 --- a/p2p/listener.go +++ /dev/null @@ -1,212 +0,0 @@ -package p2p - -import ( - "fmt" - "net" - "strconv" - "time" - - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/p2p/upnp" -) - -type Listener interface { - Connections() <-chan net.Conn - InternalAddress() *NetAddress - ExternalAddress() *NetAddress - String() string - Stop() bool -} - -// Implements Listener -type DefaultListener struct { - BaseService - - listener net.Listener - intAddr *NetAddress - extAddr *NetAddress - connections chan net.Conn -} - -const ( - numBufferedConnections = 10 - defaultExternalPort = 8770 - tryListenSeconds = 5 -) - -func splitHostPort(addr string) (host string, port int) { - host, portStr, err := net.SplitHostPort(addr) - if err != nil { - PanicSanity(err) - } - port, err = strconv.Atoi(portStr) - if err != nil { - PanicSanity(err) - } - return host, port -} - -func NewDefaultListener(protocol string, lAddr string) Listener { - // Local listen IP & port - lAddrIP, lAddrPort := splitHostPort(lAddr) - - // Create listener - var listener net.Listener - var err error - for i := 0; i < tryListenSeconds; i++ { - listener, err = net.Listen(protocol, lAddr) - if err == nil { - break - } else if i < tryListenSeconds-1 { - time.Sleep(time.Second * 1) - } - } - if err != nil { - PanicCrisis(err) - } - // Actual listener local IP & port - listenerIP, listenerPort := splitHostPort(listener.Addr().String()) - log.Info("Local listener", "ip", listenerIP, "port", listenerPort) - - // Determine internal address... - var intAddr *NetAddress = NewNetAddressString(lAddr) - - // Determine external address... - var extAddr *NetAddress - if !config.GetBool("skip_upnp") { - // If the lAddrIP is INADDR_ANY, try UPnP - if lAddrIP == "" || lAddrIP == "0.0.0.0" { - extAddr = getUPNPExternalAddress(lAddrPort, listenerPort) - } - } - // Otherwise just use the local address... - if extAddr == nil { - extAddr = getNaiveExternalAddress(listenerPort) - } - if extAddr == nil { - PanicCrisis("Could not determine external address!") - } - - dl := &DefaultListener{ - listener: listener, - intAddr: intAddr, - extAddr: extAddr, - connections: make(chan net.Conn, numBufferedConnections), - } - dl.BaseService = *NewBaseService(log, "DefaultListener", dl) - dl.Start() // Started upon construction - return dl -} - -func (l *DefaultListener) OnStart() error { - l.BaseService.OnStart() - go l.listenRoutine() - return nil -} - -func (l *DefaultListener) OnStop() { - l.BaseService.OnStop() - l.listener.Close() -} - -// Accept connections and pass on the channel -func (l *DefaultListener) listenRoutine() { - for { - conn, err := l.listener.Accept() - - if !l.IsRunning() { - break // Go to cleanup - } - - // listener wasn't stopped, - // yet we encountered an error. - if err != nil { - PanicCrisis(err) - } - - l.connections <- conn - } - - // Cleanup - close(l.connections) - for _ = range l.connections { - // Drain - } -} - -// A channel of inbound connections. -// It gets closed when the listener closes. -func (l *DefaultListener) Connections() <-chan net.Conn { - return l.connections -} - -func (l *DefaultListener) InternalAddress() *NetAddress { - return l.intAddr -} - -func (l *DefaultListener) ExternalAddress() *NetAddress { - return l.extAddr -} - -// NOTE: The returned listener is already Accept()'ing. -// So it's not suitable to pass into http.Serve(). -func (l *DefaultListener) NetListener() net.Listener { - return l.listener -} - -func (l *DefaultListener) String() string { - return fmt.Sprintf("Listener(@%v)", l.extAddr) -} - -/* external address helpers */ - -// UPNP external address discovery & port mapping -func getUPNPExternalAddress(externalPort, internalPort int) *NetAddress { - log.Info("Getting UPNP external address") - nat, err := upnp.Discover() - if err != nil { - log.Info("Could not perform UPNP discover", "error", err) - return nil - } - - ext, err := nat.GetExternalAddress() - if err != nil { - log.Info("Could not get UPNP external address", "error", err) - return nil - } - - // UPnP can't seem to get the external port, so let's just be explicit. - if externalPort == 0 { - externalPort = defaultExternalPort - } - - externalPort, err = nat.AddPortMapping("tcp", externalPort, internalPort, "tendermint", 0) - if err != nil { - log.Info("Could not add UPNP port mapping", "error", err) - return nil - } - - log.Info("Got UPNP external address", "address", ext) - return NewNetAddressIPPort(ext, uint16(externalPort)) -} - -// TODO: use syscalls: http://pastebin.com/9exZG4rh -func getNaiveExternalAddress(port int) *NetAddress { - addrs, err := net.InterfaceAddrs() - if err != nil { - PanicCrisis(Fmt("Could not fetch interface addresses: %v", err)) - } - - for _, a := range addrs { - ipnet, ok := a.(*net.IPNet) - if !ok { - continue - } - v4 := ipnet.IP.To4() - if v4 == nil || v4[0] == 127 { - continue - } // loopback - return NewNetAddressIPPort(ipnet.IP, uint16(port)) - } - return nil -} diff --git a/p2p/log.go b/p2p/log.go deleted file mode 100644 index 7802aa76..00000000 --- a/p2p/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package p2p - -import ( - "github.com/tendermint/tendermint/logger" -) - -var log = logger.New("module", "p2p") diff --git a/p2p/netaddress.go b/p2p/netaddress.go deleted file mode 100644 index f6567e05..00000000 --- a/p2p/netaddress.go +++ /dev/null @@ -1,217 +0,0 @@ -// Modified for Tendermint -// Originally Copyright (c) 2013-2014 Conformal Systems LLC. -// https://github.com/conformal/btcd/blob/master/LICENSE - -package p2p - -import ( - "fmt" - "net" - "strconv" - "time" - - . "github.com/tendermint/tendermint/common" -) - -type NetAddress struct { - IP net.IP - Port uint16 - str string -} - -// TODO: socks proxies? -func NewNetAddress(addr net.Addr) *NetAddress { - tcpAddr, ok := addr.(*net.TCPAddr) - if !ok { - PanicSanity(fmt.Sprintf("Only TCPAddrs are supported. Got: %v", addr)) - } - ip := tcpAddr.IP - port := uint16(tcpAddr.Port) - return NewNetAddressIPPort(ip, port) -} - -// Also resolves the host if host is not an IP. -func NewNetAddressString(addr string) *NetAddress { - host, portStr, err := net.SplitHostPort(addr) - if err != nil { - PanicSanity(err) - } - ip := net.ParseIP(host) - if ip == nil { - if len(host) > 0 { - ips, err := net.LookupIP(host) - if err != nil { - PanicSanity(err) - } - ip = ips[0] - } - } - port, err := strconv.ParseUint(portStr, 10, 16) - if err != nil { - PanicSanity(err) - } - na := NewNetAddressIPPort(ip, uint16(port)) - return na -} - -func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { - na := &NetAddress{ - IP: ip, - Port: port, - str: net.JoinHostPort( - ip.String(), - strconv.FormatUint(uint64(port), 10), - ), - } - return na -} - -func (na *NetAddress) Equals(other interface{}) bool { - if o, ok := other.(*NetAddress); ok { - return na.String() == o.String() - } else { - return false - } -} - -func (na *NetAddress) Less(other interface{}) bool { - if o, ok := other.(*NetAddress); ok { - return na.String() < o.String() - } else { - PanicSanity("Cannot compare unequal types") - return false - } -} - -func (na *NetAddress) String() string { - if na.str == "" { - na.str = net.JoinHostPort( - na.IP.String(), - strconv.FormatUint(uint64(na.Port), 10), - ) - } - return na.str -} - -func (na *NetAddress) Dial() (net.Conn, error) { - conn, err := net.Dial("tcp", na.String()) - if err != nil { - return nil, err - } - return conn, nil -} - -func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) { - conn, err := net.DialTimeout("tcp", na.String(), timeout) - if err != nil { - return nil, err - } - return conn, nil -} - -func (na *NetAddress) Routable() bool { - if config.GetBool("local_routing") { - return na.Valid() - } - - // TODO(oga) bitcoind doesn't include RFC3849 here, but should we? - return na.Valid() && !(na.RFC1918() || na.RFC3927() || na.RFC4862() || - na.RFC4193() || na.RFC4843() || na.Local()) -} - -// For IPv4 these are either a 0 or all bits set address. For IPv6 a zero -// address or one that matches the RFC3849 documentation address format. -func (na *NetAddress) Valid() bool { - return na.IP != nil && !(na.IP.IsUnspecified() || na.RFC3849() || - na.IP.Equal(net.IPv4bcast)) -} - -func (na *NetAddress) Local() bool { - return na.IP.IsLoopback() || zero4.Contains(na.IP) -} - -func (na *NetAddress) ReachabilityTo(o *NetAddress) int { - const ( - Unreachable = 0 - Default = iota - Teredo - Ipv6_weak - Ipv4 - Ipv6_strong - Private - ) - if !na.Routable() { - return Unreachable - } else if na.RFC4380() { - if !o.Routable() { - return Default - } else if o.RFC4380() { - return Teredo - } else if o.IP.To4() != nil { - return Ipv4 - } else { // ipv6 - return Ipv6_weak - } - } else if na.IP.To4() != nil { - if o.Routable() && o.IP.To4() != nil { - return Ipv4 - } - return Default - } else /* ipv6 */ { - var tunnelled bool - // Is our v6 is tunnelled? - if o.RFC3964() || o.RFC6052() || o.RFC6145() { - tunnelled = true - } - if !o.Routable() { - return Default - } else if o.RFC4380() { - return Teredo - } else if o.IP.To4() != nil { - return Ipv4 - } else if tunnelled { - // only prioritise ipv6 if we aren't tunnelling it. - return Ipv6_weak - } - return Ipv6_strong - } -} - -// RFC1918: IPv4 Private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) -// RFC3849: IPv6 Documentation address (2001:0DB8::/32) -// RFC3927: IPv4 Autoconfig (169.254.0.0/16) -// RFC3964: IPv6 6to4 (2002::/16) -// RFC4193: IPv6 unique local (FC00::/7) -// RFC4380: IPv6 Teredo tunneling (2001::/32) -// RFC4843: IPv6 ORCHID: (2001:10::/28) -// RFC4862: IPv6 Autoconfig (FE80::/64) -// RFC6052: IPv6 well known prefix (64:FF9B::/96) -// RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96 -var rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)} -var rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)} -var rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)} -var rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)} -var rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)} -var rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)} -var rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)} -var rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)} -var rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)} -var rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)} -var rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)} -var rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)} -var zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)} - -func (na *NetAddress) RFC1918() bool { - return rfc1918_10.Contains(na.IP) || - rfc1918_192.Contains(na.IP) || - rfc1918_172.Contains(na.IP) -} -func (na *NetAddress) RFC3849() bool { return rfc3849.Contains(na.IP) } -func (na *NetAddress) RFC3927() bool { return rfc3927.Contains(na.IP) } -func (na *NetAddress) RFC3964() bool { return rfc3964.Contains(na.IP) } -func (na *NetAddress) RFC4193() bool { return rfc4193.Contains(na.IP) } -func (na *NetAddress) RFC4380() bool { return rfc4380.Contains(na.IP) } -func (na *NetAddress) RFC4843() bool { return rfc4843.Contains(na.IP) } -func (na *NetAddress) RFC4862() bool { return rfc4862.Contains(na.IP) } -func (na *NetAddress) RFC6052() bool { return rfc6052.Contains(na.IP) } -func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) } diff --git a/p2p/peer.go b/p2p/peer.go deleted file mode 100644 index a0d8fd6c..00000000 --- a/p2p/peer.go +++ /dev/null @@ -1,134 +0,0 @@ -package p2p - -import ( - "fmt" - "io" - "net" - - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" -) - -type Peer struct { - BaseService - - outbound bool - mconn *MConnection - - *types.NodeInfo - Key string - Data *CMap // User data. -} - -// NOTE: blocking -// Before creating a peer with newPeer(), perform a handshake on connection. -func peerHandshake(conn net.Conn, ourNodeInfo *types.NodeInfo) (*types.NodeInfo, error) { - var peerNodeInfo = new(types.NodeInfo) - var err1 error - var err2 error - Parallel( - func() { - var n int64 - wire.WriteBinary(ourNodeInfo, conn, &n, &err1) - }, - func() { - var n int64 - wire.ReadBinary(peerNodeInfo, conn, &n, &err2) - log.Notice("Peer handshake", "peerNodeInfo", peerNodeInfo) - }) - if err1 != nil { - return nil, err1 - } - if err2 != nil { - return nil, err2 - } - return peerNodeInfo, nil -} - -// NOTE: call peerHandshake on conn before calling newPeer(). -func newPeer(conn net.Conn, peerNodeInfo *types.NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer { - var p *Peer - onReceive := func(chID byte, msgBytes []byte) { - reactor := reactorsByCh[chID] - if reactor == nil { - PanicSanity(Fmt("Unknown channel %X", chID)) - } - reactor.Receive(chID, p, msgBytes) - } - onError := func(r interface{}) { - p.Stop() - onPeerError(p, r) - } - mconn := NewMConnection(conn, chDescs, onReceive, onError) - p = &Peer{ - outbound: outbound, - mconn: mconn, - NodeInfo: peerNodeInfo, - Key: peerNodeInfo.PubKey.KeyString(), - Data: NewCMap(), - } - p.BaseService = *NewBaseService(log, "Peer", p) - return p -} - -func (p *Peer) OnStart() error { - p.BaseService.OnStart() - _, err := p.mconn.Start() - return err -} - -func (p *Peer) OnStop() { - p.BaseService.OnStop() - p.mconn.Stop() -} - -func (p *Peer) Connection() *MConnection { - return p.mconn -} - -func (p *Peer) IsOutbound() bool { - return p.outbound -} - -func (p *Peer) Send(chID byte, msg interface{}) bool { - if !p.IsRunning() { - return false - } - return p.mconn.Send(chID, msg) -} - -func (p *Peer) TrySend(chID byte, msg interface{}) bool { - if !p.IsRunning() { - return false - } - return p.mconn.TrySend(chID, msg) -} - -func (p *Peer) CanSend(chID byte) bool { - if !p.IsRunning() { - return false - } - return p.mconn.CanSend(chID) -} - -func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { - wire.WriteString(p.Key, w, &n, &err) - return -} - -func (p *Peer) String() string { - if p.outbound { - return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.Key[:12]) - } else { - return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12]) - } -} - -func (p *Peer) Equals(other *Peer) bool { - return p.Key == other.Key -} - -func (p *Peer) Get(key string) interface{} { - return p.Data.Get(key) -} diff --git a/p2p/peer_set.go b/p2p/peer_set.go deleted file mode 100644 index 8a5f8e6d..00000000 --- a/p2p/peer_set.go +++ /dev/null @@ -1,227 +0,0 @@ -package p2p - -import ( - "net" - "strings" - "sync" -) - -// IPeerSet has a (immutable) subset of the methods of PeerSet. -type IPeerSet interface { - Has(key string) bool - Get(key string) *Peer - List() []*Peer - Size() int -} - -//----------------------------------------------------------------------------- - -var ( - maxPeersPerIPRange = [4]int{11, 7, 5, 3} // ... -) - -// PeerSet is a special structure for keeping a table of peers. -// Iteration over the peers is super fast and thread-safe. -// We also track how many peers per IP range and avoid too many -type PeerSet struct { - mtx sync.Mutex - lookup map[string]*peerSetItem - list []*Peer - connectedIPs *nestedCounter -} - -type peerSetItem struct { - peer *Peer - index int -} - -func NewPeerSet() *PeerSet { - return &PeerSet{ - lookup: make(map[string]*peerSetItem), - list: make([]*Peer, 0, 256), - connectedIPs: NewNestedCounter(), - } -} - -// Returns false if peer with key (PubKeyEd25519) is already in set -// or if we have too many peers from the peer's IP range -func (ps *PeerSet) Add(peer *Peer) error { - ps.mtx.Lock() - defer ps.mtx.Unlock() - if ps.lookup[peer.Key] != nil { - return ErrSwitchDuplicatePeer - } - - // ensure we havent maxed out connections for the peer's IP range yet - // and update the IP range counters - if !ps.incrIPRangeCounts(peer.Host) { - return ErrSwitchMaxPeersPerIPRange - } - - index := len(ps.list) - // Appending is safe even with other goroutines - // iterating over the ps.list slice. - ps.list = append(ps.list, peer) - ps.lookup[peer.Key] = &peerSetItem{peer, index} - return nil -} - -func (ps *PeerSet) Has(peerKey string) bool { - ps.mtx.Lock() - defer ps.mtx.Unlock() - _, ok := ps.lookup[peerKey] - return ok -} - -func (ps *PeerSet) Get(peerKey string) *Peer { - ps.mtx.Lock() - defer ps.mtx.Unlock() - item, ok := ps.lookup[peerKey] - if ok { - return item.peer - } else { - return nil - } -} - -func (ps *PeerSet) Remove(peer *Peer) { - ps.mtx.Lock() - defer ps.mtx.Unlock() - item := ps.lookup[peer.Key] - if item == nil { - return - } - - // update the IP range counters - ps.decrIPRangeCounts(peer.Host) - - index := item.index - // Copy the list but without the last element. - // (we must copy because we're mutating the list) - newList := make([]*Peer, len(ps.list)-1) - copy(newList, ps.list) - // If it's the last peer, that's an easy special case. - if index == len(ps.list)-1 { - ps.list = newList - delete(ps.lookup, peer.Key) - return - } - - // Move the last item from ps.list to "index" in list. - lastPeer := ps.list[len(ps.list)-1] - lastPeerKey := lastPeer.Key - lastPeerItem := ps.lookup[lastPeerKey] - newList[index] = lastPeer - lastPeerItem.index = index - ps.list = newList - delete(ps.lookup, peer.Key) - -} - -func (ps *PeerSet) Size() int { - ps.mtx.Lock() - defer ps.mtx.Unlock() - return len(ps.list) -} - -// threadsafe list of peers. -func (ps *PeerSet) List() []*Peer { - ps.mtx.Lock() - defer ps.mtx.Unlock() - return ps.list -} - -//----------------------------------------------------------------------------- -// track the number of IPs we're connected to for each IP address range - -// forms an IP address hierarchy tree with counts -// the struct itself is not thread safe and should always only be accessed with the ps.mtx locked -type nestedCounter struct { - count int - children map[string]*nestedCounter -} - -func NewNestedCounter() *nestedCounter { - nc := new(nestedCounter) - nc.children = make(map[string]*nestedCounter) - return nc -} - -// Check if we have too many IPs in the IP range of the incoming connection -// Thread safe -func (ps *PeerSet) HasMaxForIPRange(conn net.Conn) (ok bool) { - ps.mtx.Lock() - defer ps.mtx.Unlock() - ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String()) - ipBytes := strings.Split(ip, ".") - - c := ps.connectedIPs - for i, ipByte := range ipBytes { - if c, ok = c.children[ipByte]; !ok { - return false - } - if maxPeersPerIPRange[i] <= c.count { - return true - } - } - return false -} - -// Increments counts for this address' IP range -// Returns false if we already have enough connections -// Not thread safe (only called by ps.Add()) -func (ps *PeerSet) incrIPRangeCounts(address string) bool { - addrParts := strings.Split(address, ".") - - c := ps.connectedIPs - return incrNestedCounters(c, addrParts, 0) -} - -// Recursively descend the IP hierarchy, checking if we have -// max peers for each range and incrementing if not. -// Returns false if incr failed because max peers reached for some range counter. -func incrNestedCounters(c *nestedCounter, ipBytes []string, index int) bool { - ipByte := ipBytes[index] - child := c.children[ipByte] - if child == nil { - child = NewNestedCounter() - c.children[ipByte] = child - } - if index+1 < len(ipBytes) { - if !incrNestedCounters(child, ipBytes, index+1) { - return false - } - } - if maxPeersPerIPRange[index] <= child.count { - return false - } else { - child.count += 1 - return true - } -} - -// Decrement counts for this address' IP range -func (ps *PeerSet) decrIPRangeCounts(address string) { - addrParts := strings.Split(address, ".") - - c := ps.connectedIPs - decrNestedCounters(c, addrParts, 0) -} - -// Recursively descend the IP hierarchy, decrementing by one. -// If the counter is zero, deletes the child. -func decrNestedCounters(c *nestedCounter, ipBytes []string, index int) { - ipByte := ipBytes[index] - child := c.children[ipByte] - if child == nil { - log.Error("p2p/peer_set decrNestedCounters encountered a missing child counter") - return - } - if index+1 < len(ipBytes) { - decrNestedCounters(child, ipBytes, index+1) - } - child.count -= 1 - if child.count <= 0 { - delete(c.children, ipByte) - } -} diff --git a/p2p/peer_set_test.go b/p2p/peer_set_test.go deleted file mode 100644 index 90bd8670..00000000 --- a/p2p/peer_set_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package p2p - -import ( - "math/rand" - "strings" - "testing" - - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/types" -) - -// Returns an empty dummy peer -func randPeer() *Peer { - return &Peer{ - Key: RandStr(12), - NodeInfo: &types.NodeInfo{ - Host: Fmt("%v.%v.%v.%v", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), - }, - } -} - -func TestAddRemoveOne(t *testing.T) { - peerSet := NewPeerSet() - - peer := randPeer() - err := peerSet.Add(peer) - if err != nil { - t.Errorf("Failed to add new peer") - } - if peerSet.Size() != 1 { - t.Errorf("Failed to add new peer and increment size") - } - - peerSet.Remove(peer) - if peerSet.Has(peer.Key) { - t.Errorf("Failed to remove peer") - } - if peerSet.Size() != 0 { - t.Errorf("Failed to remove peer and decrement size") - } -} - -func TestAddRemoveMany(t *testing.T) { - peerSet := NewPeerSet() - - peers := []*Peer{} - N := 100 - maxPeersPerIPRange = [4]int{N, N, N, N} - for i := 0; i < N; i++ { - peer := randPeer() - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - if peerSet.Size() != i+1 { - t.Errorf("Failed to add new peer and increment size") - } - peers = append(peers, peer) - } - - for i, peer := range peers { - peerSet.Remove(peer) - if peerSet.Has(peer.Key) { - t.Errorf("Failed to remove peer") - } - if peerSet.Size() != len(peers)-i-1 { - t.Errorf("Failed to remove peer and decrement size") - } - } -} - -func newPeerInIPRange(ipBytes ...string) *Peer { - ips := make([]string, 4) - for i, ipByte := range ipBytes { - ips[i] = ipByte - } - for i := len(ipBytes); i < 4; i++ { - ips[i] = Fmt("%v", rand.Int()%256) - } - ipS := strings.Join(ips, ".") - return &Peer{ - Key: RandStr(12), - NodeInfo: &types.NodeInfo{ - Host: ipS, - }, - } -} - -func TestIPRanges(t *testing.T) { - peerSet := NewPeerSet() - - // test /8 - maxPeersPerIPRange = [4]int{2, 2, 2, 2} - peer := newPeerInIPRange("54", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "2") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "3") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("55", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - - // test /16 - peerSet = NewPeerSet() - maxPeersPerIPRange = [4]int{3, 2, 1, 1} - peer = newPeerInIPRange("54", "112", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "2") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "3") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("54", "113", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - - // test /24 - peerSet = NewPeerSet() - maxPeersPerIPRange = [4]int{5, 3, 2, 1} - peer = newPeerInIPRange("54", "112", "11", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "2") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "3") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("54", "112", "12", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - - // test /32 - peerSet = NewPeerSet() - maxPeersPerIPRange = [4]int{11, 7, 5, 2} - peer = newPeerInIPRange("54", "112", "11", "10") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "10") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "10") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("54", "112", "11", "11") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } -} diff --git a/p2p/pex_reactor.go b/p2p/pex_reactor.go deleted file mode 100644 index e203063c..00000000 --- a/p2p/pex_reactor.go +++ /dev/null @@ -1,262 +0,0 @@ -package p2p - -import ( - "bytes" - "errors" - "fmt" - "math/rand" - "reflect" - "time" - - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/events" - "github.com/tendermint/tendermint/wire" -) - -var pexErrInvalidMessage = errors.New("Invalid PEX message") - -const ( - PexChannel = byte(0x00) - ensurePeersPeriodSeconds = 30 - minNumOutboundPeers = 10 -) - -/* -PEXReactor handles PEX (peer exchange) and ensures that an -adequate number of peers are connected to the switch. -*/ -type PEXReactor struct { - BaseReactor - - sw *Switch - book *AddrBook - evsw events.Fireable -} - -func NewPEXReactor(book *AddrBook) *PEXReactor { - pexR := &PEXReactor{ - book: book, - } - pexR.BaseReactor = *NewBaseReactor(log, "PEXReactor", pexR) - return pexR -} - -func (pexR *PEXReactor) OnStart() error { - pexR.BaseReactor.OnStart() - go pexR.ensurePeersRoutine() - return nil -} - -func (pexR *PEXReactor) OnStop() { - pexR.BaseReactor.OnStop() -} - -// Implements Reactor -func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { - return []*ChannelDescriptor{ - &ChannelDescriptor{ - ID: PexChannel, - Priority: 1, - SendQueueCapacity: 10, - }, - } -} - -// Implements Reactor -func (pexR *PEXReactor) AddPeer(peer *Peer) { - // Add the peer to the address book - netAddr := NewNetAddressString(fmt.Sprintf("%s:%d", peer.Host, peer.P2PPort)) - if peer.IsOutbound() { - if pexR.book.NeedMoreAddrs() { - pexR.RequestPEX(peer) - } - } else { - // For inbound connections, the peer is its own source - // (For outbound peers, the address is already in the books) - pexR.book.AddAddress(netAddr, netAddr) - } -} - -// Implements Reactor -func (pexR *PEXReactor) RemovePeer(peer *Peer, reason interface{}) { - // TODO -} - -// Implements Reactor -// Handles incoming PEX messages. -func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { - - // decode message - _, msg, err := DecodeMessage(msgBytes) - if err != nil { - log.Warn("Error decoding message", "error", err) - return - } - log.Notice("Received message", "msg", msg) - - switch msg := msg.(type) { - case *pexRequestMessage: - // src requested some peers. - // TODO: prevent abuse. - pexR.SendAddrs(src, pexR.book.GetSelection()) - case *pexAddrsMessage: - // We received some peer addresses from src. - // TODO: prevent abuse. - // (We don't want to get spammed with bad peers) - srcAddr := src.Connection().RemoteAddress - for _, addr := range msg.Addrs { - pexR.book.AddAddress(addr, srcAddr) - } - default: - log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) - } - -} - -// Asks peer for more addresses. -func (pexR *PEXReactor) RequestPEX(peer *Peer) { - peer.Send(PexChannel, &pexRequestMessage{}) -} - -func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) { - peer.Send(PexChannel, &pexAddrsMessage{Addrs: addrs}) -} - -// Ensures that sufficient peers are connected. (continuous) -func (pexR *PEXReactor) ensurePeersRoutine() { - // Randomize when routine starts - time.Sleep(time.Duration(rand.Int63n(500*ensurePeersPeriodSeconds)) * time.Millisecond) - - // fire once immediately. - pexR.ensurePeers() - // fire periodically - timer := NewRepeatTimer("pex", ensurePeersPeriodSeconds*time.Second) -FOR_LOOP: - for { - select { - case <-timer.Ch: - pexR.ensurePeers() - case <-pexR.Quit: - break FOR_LOOP - } - } - - // Cleanup - timer.Stop() -} - -// Ensures that sufficient peers are connected. (once) -func (pexR *PEXReactor) ensurePeers() { - numOutPeers, _, numDialing := pexR.Switch.NumPeers() - numToDial := minNumOutboundPeers - (numOutPeers + numDialing) - log.Info("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial) - if numToDial <= 0 { - return - } - toDial := NewCMap() - - // Try to pick numToDial addresses to dial. - // TODO: improve logic. - for i := 0; i < numToDial; i++ { - newBias := MinInt(numOutPeers, 8)*10 + 10 - var picked *NetAddress - // Try to fetch a new peer 3 times. - // This caps the maximum number of tries to 3 * numToDial. - for j := 0; j < 3; j++ { - try := pexR.book.PickAddress(newBias) - if try == nil { - break - } - alreadySelected := toDial.Has(try.IP.String()) - alreadyDialing := pexR.Switch.IsDialing(try) - alreadyConnected := pexR.Switch.Peers().Has(try.IP.String()) - if alreadySelected || alreadyDialing || alreadyConnected { - /* - log.Info("Cannot dial address", "addr", try, - "alreadySelected", alreadySelected, - "alreadyDialing", alreadyDialing, - "alreadyConnected", alreadyConnected) - */ - continue - } else { - log.Info("Will dial address", "addr", try) - picked = try - break - } - } - if picked == nil { - continue - } - toDial.Set(picked.IP.String(), picked) - } - - // Dial picked addresses - for _, item := range toDial.Values() { - go func(picked *NetAddress) { - _, err := pexR.Switch.DialPeerWithAddress(picked) - if err != nil { - pexR.book.MarkAttempt(picked) - } - }(item.(*NetAddress)) - } - - // If we need more addresses, pick a random peer and ask for more. - if pexR.book.NeedMoreAddrs() { - if peers := pexR.Switch.Peers().List(); len(peers) > 0 { - i := rand.Int() % len(peers) - peer := peers[i] - log.Info("No addresses to dial. Sending pexRequest to random peer", "peer", peer) - pexR.RequestPEX(peer) - } - } -} - -// implements events.Eventable -func (pexR *PEXReactor) SetFireable(evsw events.Fireable) { - pexR.evsw = evsw -} - -//----------------------------------------------------------------------------- -// Messages - -const ( - msgTypeRequest = byte(0x01) - msgTypeAddrs = byte(0x02) -) - -type PexMessage interface{} - -var _ = wire.RegisterInterface( - struct{ PexMessage }{}, - wire.ConcreteType{&pexRequestMessage{}, msgTypeRequest}, - wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs}, -) - -func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) { - msgType = bz[0] - n := new(int64) - r := bytes.NewReader(bz) - msg = wire.ReadBinary(struct{ PexMessage }{}, r, n, &err).(struct{ PexMessage }).PexMessage - return -} - -/* -A pexRequestMessage requests additional peer addresses. -*/ -type pexRequestMessage struct { -} - -func (m *pexRequestMessage) String() string { - return "[pexRequest]" -} - -/* -A message with announced peer addresses. -*/ -type pexAddrsMessage struct { - Addrs []*NetAddress -} - -func (m *pexAddrsMessage) String() string { - return fmt.Sprintf("[pexAddrs %v]", m.Addrs) -} diff --git a/p2p/secret_connection.go b/p2p/secret_connection.go deleted file mode 100644 index a8360ac9..00000000 --- a/p2p/secret_connection.go +++ /dev/null @@ -1,346 +0,0 @@ -// Uses nacl's secret_box to encrypt a net.Conn. -// It is (meant to be) an implementation of the STS protocol. -// Note we do not (yet) assume that a remote peer's pubkey -// is known ahead of time, and thus we are technically -// still vulnerable to MITM. (TODO!) -// See docs/sts-final.pdf for more info -package p2p - -import ( - "bytes" - crand "crypto/rand" - "crypto/sha256" - "encoding/binary" - "errors" - "io" - "net" - "time" - - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/nacl/box" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/nacl/secretbox" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/ripemd160" - - acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" -) - -// 2 + 1024 == 1026 total frame size -const dataLenSize = 2 // uint16 to describe the length, is <= dataMaxSize -const dataMaxSize = 1024 -const totalFrameSize = dataMaxSize + dataLenSize -const sealedFrameSize = totalFrameSize + secretbox.Overhead -const authSigMsgSize = (32 + 1) + (64 + 1) // fixed size (length prefixed) byte arrays - -// Implements net.Conn -type SecretConnection struct { - conn io.ReadWriteCloser - recvBuffer []byte - recvNonce *[24]byte - sendNonce *[24]byte - remPubKey acm.PubKeyEd25519 - shrSecret *[32]byte // shared secret -} - -// Performs handshake and returns a new authenticated SecretConnection. -// Returns nil if error in handshake. -// Caller should call conn.Close() -// See docs/sts-final.pdf for more information. -func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey acm.PrivKeyEd25519) (*SecretConnection, error) { - - locPubKey := locPrivKey.PubKey().(acm.PubKeyEd25519) - - // Generate ephemeral keys for perfect forward secrecy. - locEphPub, locEphPriv := genEphKeys() - - // Write local ephemeral pubkey and receive one too. - // NOTE: every 32-byte string is accepted as a Curve25519 public key - // (see DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf) - remEphPub, err := shareEphPubKey(conn, locEphPub) - if err != nil { - return nil, err - } - - // Compute common shared secret. - shrSecret := computeSharedSecret(remEphPub, locEphPriv) - - // Sort by lexical order. - loEphPub, hiEphPub := sort32(locEphPub, remEphPub) - - // Generate nonces to use for secretbox. - recvNonce, sendNonce := genNonces(loEphPub, hiEphPub, locEphPub == loEphPub) - - // Generate common challenge to sign. - challenge := genChallenge(loEphPub, hiEphPub) - - // Construct SecretConnection. - sc := &SecretConnection{ - conn: conn, - recvBuffer: nil, - recvNonce: recvNonce, - sendNonce: sendNonce, - shrSecret: shrSecret, - } - - // Sign the challenge bytes for authentication. - locSignature := signChallenge(challenge, locPrivKey) - - // Share (in secret) each other's pubkey & challenge signature - authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature) - if err != nil { - return nil, err - } - remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig - if !remPubKey.VerifyBytes(challenge[:], remSignature) { - return nil, errors.New("Challenge verification failed") - } - - // We've authorized. - sc.remPubKey = remPubKey - return sc, nil -} - -// Returns authenticated remote pubkey -func (sc *SecretConnection) RemotePubKey() acm.PubKeyEd25519 { - return sc.remPubKey -} - -// Writes encrypted frames of `sealedFrameSize` -// CONTRACT: data smaller than dataMaxSize is read atomically. -func (sc *SecretConnection) Write(data []byte) (n int, err error) { - for 0 < len(data) { - var frame []byte = make([]byte, totalFrameSize) - var chunk []byte - if dataMaxSize < len(data) { - chunk = data[:dataMaxSize] - data = data[dataMaxSize:] - } else { - chunk = data - data = nil - } - chunkLength := len(chunk) - binary.BigEndian.PutUint16(frame, uint16(chunkLength)) - copy(frame[dataLenSize:], chunk) - - // encrypt the frame - var sealedFrame = make([]byte, sealedFrameSize) - secretbox.Seal(sealedFrame[:0], frame, sc.sendNonce, sc.shrSecret) - // fmt.Printf("secretbox.Seal(sealed:%X,sendNonce:%X,shrSecret:%X\n", sealedFrame, sc.sendNonce, sc.shrSecret) - incr2Nonce(sc.sendNonce) - // end encryption - - _, err := sc.conn.Write(sealedFrame) - if err != nil { - return n, err - } else { - n += len(chunk) - } - } - return -} - -// CONTRACT: data smaller than dataMaxSize is read atomically. -func (sc *SecretConnection) Read(data []byte) (n int, err error) { - if 0 < len(sc.recvBuffer) { - n_ := copy(data, sc.recvBuffer) - sc.recvBuffer = sc.recvBuffer[n_:] - return - } - - sealedFrame := make([]byte, sealedFrameSize) - _, err = io.ReadFull(sc.conn, sealedFrame) - if err != nil { - return - } - - // decrypt the frame - var frame = make([]byte, totalFrameSize) - // fmt.Printf("secretbox.Open(sealed:%X,recvNonce:%X,shrSecret:%X\n", sealedFrame, sc.recvNonce, sc.shrSecret) - _, ok := secretbox.Open(frame[:0], sealedFrame, sc.recvNonce, sc.shrSecret) - if !ok { - return n, errors.New("Failed to decrypt SecretConnection") - } - incr2Nonce(sc.recvNonce) - // end decryption - - var chunkLength = binary.BigEndian.Uint16(frame) // read the first two bytes - if chunkLength > dataMaxSize { - return 0, errors.New("chunkLength is greater than dataMaxSize") - } - var chunk = frame[dataLenSize : dataLenSize+chunkLength] - - n = copy(data, chunk) - sc.recvBuffer = chunk[n:] - return -} - -// Implements net.Conn -func (sc *SecretConnection) Close() error { return sc.conn.Close() } -func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() } -func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() } -func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) } -func (sc *SecretConnection) SetReadDeadline(t time.Time) error { - return sc.conn.(net.Conn).SetReadDeadline(t) -} -func (sc *SecretConnection) SetWriteDeadline(t time.Time) error { - return sc.conn.(net.Conn).SetWriteDeadline(t) -} - -func genEphKeys() (ephPub, ephPriv *[32]byte) { - var err error - ephPub, ephPriv, err = box.GenerateKey(crand.Reader) - if err != nil { - PanicCrisis("Could not generate ephemeral keypairs") - } - return -} - -func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) { - var err1, err2 error - - Parallel( - func() { - _, err1 = conn.Write(locEphPub[:]) - }, - func() { - remEphPub = new([32]byte) - _, err2 = io.ReadFull(conn, remEphPub[:]) - }, - ) - - if err1 != nil { - return nil, err1 - } - if err2 != nil { - return nil, err2 - } - - return remEphPub, nil -} - -func computeSharedSecret(remPubKey, locPrivKey *[32]byte) (shrSecret *[32]byte) { - shrSecret = new([32]byte) - box.Precompute(shrSecret, remPubKey, locPrivKey) - return -} - -func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) { - if bytes.Compare(foo[:], bar[:]) < 0 { - lo = foo - hi = bar - } else { - lo = bar - hi = foo - } - return -} - -func genNonces(loPubKey, hiPubKey *[32]byte, locIsLo bool) (recvNonce, sendNonce *[24]byte) { - nonce1 := hash24(append(loPubKey[:], hiPubKey[:]...)) - nonce2 := new([24]byte) - copy(nonce2[:], nonce1[:]) - nonce2[len(nonce2)-1] ^= 0x01 - if locIsLo { - recvNonce = nonce1 - sendNonce = nonce2 - } else { - recvNonce = nonce2 - sendNonce = nonce1 - } - return -} - -func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) { - return hash32(append(loPubKey[:], hiPubKey[:]...)) -} - -func signChallenge(challenge *[32]byte, locPrivKey acm.PrivKeyEd25519) (signature acm.SignatureEd25519) { - signature = locPrivKey.Sign(challenge[:]).(acm.SignatureEd25519) - return -} - -type authSigMessage struct { - Key acm.PubKeyEd25519 - Sig acm.SignatureEd25519 -} - -func shareAuthSignature(sc *SecretConnection, pubKey acm.PubKeyEd25519, signature acm.SignatureEd25519) (*authSigMessage, error) { - var recvMsg authSigMessage - var err1, err2 error - - Parallel( - func() { - msgBytes := wire.BinaryBytes(authSigMessage{pubKey, signature}) - _, err1 = sc.Write(msgBytes) - }, - func() { - readBuffer := make([]byte, authSigMsgSize) - _, err2 = io.ReadFull(sc, readBuffer) - if err2 != nil { - return - } - n := int64(0) // not used. - recvMsg = wire.ReadBinary(authSigMessage{}, bytes.NewBuffer(readBuffer), &n, &err2).(authSigMessage) - }) - - if err1 != nil { - return nil, err1 - } - if err2 != nil { - return nil, err2 - } - - return &recvMsg, nil -} - -func verifyChallengeSignature(challenge *[32]byte, remPubKey acm.PubKeyEd25519, remSignature acm.SignatureEd25519) bool { - return remPubKey.VerifyBytes(challenge[:], remSignature) -} - -//-------------------------------------------------------------------------------- - -// sha256 -func hash32(input []byte) (res *[32]byte) { - hasher := sha256.New() - hasher.Write(input) // does not error - resSlice := hasher.Sum(nil) - res = new([32]byte) - copy(res[:], resSlice) - return -} - -// We only fill in the first 20 bytes with ripemd160 -func hash24(input []byte) (res *[24]byte) { - hasher := ripemd160.New() - hasher.Write(input) // does not error - resSlice := hasher.Sum(nil) - res = new([24]byte) - copy(res[:], resSlice) - return -} - -// ripemd160 -func hash20(input []byte) (res *[20]byte) { - hasher := ripemd160.New() - hasher.Write(input) // does not error - resSlice := hasher.Sum(nil) - res = new([20]byte) - copy(res[:], resSlice) - return -} - -// increment nonce big-endian by 2 with wraparound. -func incr2Nonce(nonce *[24]byte) { - incrNonce(nonce) - incrNonce(nonce) -} - -// increment nonce big-endian by 1 with wraparound. -func incrNonce(nonce *[24]byte) { - for i := 23; 0 <= i; i-- { - nonce[i] += 1 - if nonce[i] != 0 { - return - } - } -} diff --git a/p2p/secret_connection_test.go b/p2p/secret_connection_test.go deleted file mode 100644 index 28921ff7..00000000 --- a/p2p/secret_connection_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package p2p - -import ( - "bytes" - "io" - "testing" - - acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" -) - -type dummyConn struct { - *io.PipeReader - *io.PipeWriter -} - -func (drw dummyConn) Close() (err error) { - err2 := drw.PipeWriter.CloseWithError(io.EOF) - err1 := drw.PipeReader.Close() - if err2 != nil { - return err - } - return err1 -} - -// Each returned ReadWriteCloser is akin to a net.Connection -func makeDummyConnPair() (fooConn, barConn dummyConn) { - barReader, fooWriter := io.Pipe() - fooReader, barWriter := io.Pipe() - return dummyConn{fooReader, fooWriter}, dummyConn{barReader, barWriter} -} - -func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection) { - fooConn, barConn := makeDummyConnPair() - fooPrvKey := acm.GenPrivKeyEd25519() - fooPubKey := fooPrvKey.PubKey().(acm.PubKeyEd25519) - barPrvKey := acm.GenPrivKeyEd25519() - barPubKey := barPrvKey.PubKey().(acm.PubKeyEd25519) - - Parallel( - func() { - var err error - fooSecConn, err = MakeSecretConnection(fooConn, fooPrvKey) - if err != nil { - tb.Errorf("Failed to establish SecretConnection for foo: %v", err) - return - } - remotePubBytes := fooSecConn.RemotePubKey() - if !bytes.Equal(remotePubBytes[:], barPubKey[:]) { - tb.Errorf("Unexpected fooSecConn.RemotePubKey. Expected %v, got %v", - barPubKey, fooSecConn.RemotePubKey()) - } - }, - func() { - var err error - barSecConn, err = MakeSecretConnection(barConn, barPrvKey) - if barSecConn == nil { - tb.Errorf("Failed to establish SecretConnection for bar: %v", err) - return - } - remotePubBytes := barSecConn.RemotePubKey() - if !bytes.Equal(remotePubBytes[:], fooPubKey[:]) { - tb.Errorf("Unexpected barSecConn.RemotePubKey. Expected %v, got %v", - fooPubKey, barSecConn.RemotePubKey()) - } - }) - - return -} - -func TestSecretConnectionHandshake(t *testing.T) { - fooSecConn, barSecConn := makeSecretConnPair(t) - fooSecConn.Close() - barSecConn.Close() -} - -func TestSecretConnectionReadWrite(t *testing.T) { - fooConn, barConn := makeDummyConnPair() - fooWrites, barWrites := []string{}, []string{} - fooReads, barReads := []string{}, []string{} - - // Pre-generate the things to write (for foo & bar) - for i := 0; i < 100; i++ { - fooWrites = append(fooWrites, RandStr((RandInt()%(dataMaxSize*5))+1)) - barWrites = append(barWrites, RandStr((RandInt()%(dataMaxSize*5))+1)) - } - - // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa - genNodeRunner := func(nodeConn dummyConn, nodeWrites []string, nodeReads *[]string) func() { - return func() { - // Node handskae - nodePrvKey := acm.GenPrivKeyEd25519() - nodeSecretConn, err := MakeSecretConnection(nodeConn, nodePrvKey) - if err != nil { - t.Errorf("Failed to establish SecretConnection for node: %v", err) - return - } - // In parallel, handle reads and writes - Parallel( - func() { - // Node writes - for _, nodeWrite := range nodeWrites { - n, err := nodeSecretConn.Write([]byte(nodeWrite)) - if err != nil { - t.Errorf("Failed to write to nodeSecretConn: %v", err) - return - } - if n != len(nodeWrite) { - t.Errorf("Failed to write all bytes. Expected %v, wrote %v", len(nodeWrite), n) - return - } - } - nodeConn.PipeWriter.Close() - }, - func() { - // Node reads - readBuffer := make([]byte, dataMaxSize) - for { - n, err := nodeSecretConn.Read(readBuffer) - if err == io.EOF { - return - } else if err != nil { - t.Errorf("Failed to read from nodeSecretConn: %v", err) - return - } - *nodeReads = append(*nodeReads, string(readBuffer[:n])) - } - nodeConn.PipeReader.Close() - }) - } - } - - // Run foo & bar in parallel - Parallel( - genNodeRunner(fooConn, fooWrites, &fooReads), - genNodeRunner(barConn, barWrites, &barReads), - ) - - // A helper to ensure that the writes and reads match. - // Additionally, small writes (<= dataMaxSize) must be atomically read. - compareWritesReads := func(writes []string, reads []string) { - for { - // Pop next write & corresponding reads - var read, write string = "", writes[0] - var readCount = 0 - for _, readChunk := range reads { - read += readChunk - readCount += 1 - if len(write) <= len(read) { - break - } - if len(write) <= dataMaxSize { - break // atomicity of small writes - } - } - // Compare - if write != read { - t.Errorf("Expected to read %X, got %X", write, read) - } - // Iterate - writes = writes[1:] - reads = reads[readCount:] - if len(writes) == 0 { - break - } - } - } - - compareWritesReads(fooWrites, barReads) - compareWritesReads(barWrites, fooReads) - -} - -func BenchmarkSecretConnection(b *testing.B) { - b.StopTimer() - fooSecConn, barSecConn := makeSecretConnPair(b) - fooWriteText := RandStr(dataMaxSize) - // Consume reads from bar's reader - go func() { - readBuffer := make([]byte, dataMaxSize) - for { - _, err := barSecConn.Read(readBuffer) - if err == io.EOF { - return - } else if err != nil { - b.Fatalf("Failed to read from barSecConn: %v", err) - } - } - }() - - b.StartTimer() - for i := 0; i < b.N; i++ { - _, err := fooSecConn.Write([]byte(fooWriteText)) - if err != nil { - b.Fatalf("Failed to write to fooSecConn: %v", err) - } - } - b.StopTimer() - - fooSecConn.Close() - //barSecConn.Close() race condition -} diff --git a/p2p/switch.go b/p2p/switch.go deleted file mode 100644 index 9d3a07d4..00000000 --- a/p2p/switch.go +++ /dev/null @@ -1,391 +0,0 @@ -package p2p - -import ( - "errors" - "fmt" - "net" - "strconv" - "time" - - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" - acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/types" -) - -type Reactor interface { - Service // Start, Stop - - SetSwitch(*Switch) - GetChannels() []*ChannelDescriptor - AddPeer(peer *Peer) - RemovePeer(peer *Peer, reason interface{}) - Receive(chID byte, peer *Peer, msgBytes []byte) -} - -//-------------------------------------- - -type BaseReactor struct { - QuitService // Provides Start, Stop, .Quit - Switch *Switch -} - -func NewBaseReactor(log log15.Logger, name string, impl Reactor) *BaseReactor { - return &BaseReactor{ - QuitService: *NewQuitService(log, name, impl), - Switch: nil, - } -} - -func (br *BaseReactor) SetSwitch(sw *Switch) { - br.Switch = sw -} -func (_ *BaseReactor) GetChannels() []*ChannelDescriptor { return nil } -func (_ *BaseReactor) AddPeer(peer *Peer) {} -func (_ *BaseReactor) RemovePeer(peer *Peer, reason interface{}) {} -func (_ *BaseReactor) Receive(chID byte, peer *Peer, msgBytes []byte) {} - -//----------------------------------------------------------------------------- - -/* -The `Switch` handles peer connections and exposes an API to receive incoming messages -on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one -or more `Channels`. So while sending outgoing messages is typically performed on the peer, -incoming messages are received on the reactor. -*/ -type Switch struct { - BaseService - - listeners []Listener - reactors map[string]Reactor - chDescs []*ChannelDescriptor - reactorsByCh map[byte]Reactor - peers *PeerSet - dialing *CMap - nodeInfo *types.NodeInfo // our node info - nodePrivKey acm.PrivKeyEd25519 // our node privkey -} - -var ( - ErrSwitchDuplicatePeer = errors.New("Duplicate peer") - ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") -) - -const ( - peerDialTimeoutSeconds = 3 // TODO make this configurable - handshakeTimeoutSeconds = 20 // TODO make this configurable - maxNumPeers = 50 // TODO make this configurable -) - -func NewSwitch() *Switch { - sw := &Switch{ - reactors: make(map[string]Reactor), - chDescs: make([]*ChannelDescriptor, 0), - reactorsByCh: make(map[byte]Reactor), - peers: NewPeerSet(), - dialing: NewCMap(), - nodeInfo: nil, - } - sw.BaseService = *NewBaseService(log, "P2P Switch", sw) - return sw -} - -// Not goroutine safe. -func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor { - // Validate the reactor. - // No two reactors can share the same channel. - reactorChannels := reactor.GetChannels() - for _, chDesc := range reactorChannels { - chID := chDesc.ID - if sw.reactorsByCh[chID] != nil { - PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor)) - } - sw.chDescs = append(sw.chDescs, chDesc) - sw.reactorsByCh[chID] = reactor - } - sw.reactors[name] = reactor - reactor.SetSwitch(sw) - return reactor -} - -// Not goroutine safe. -func (sw *Switch) Reactors() map[string]Reactor { - return sw.reactors -} - -// Not goroutine safe. -func (sw *Switch) Reactor(name string) Reactor { - return sw.reactors[name] -} - -// Not goroutine safe. -func (sw *Switch) AddListener(l Listener) { - sw.listeners = append(sw.listeners, l) -} - -// Not goroutine safe. -func (sw *Switch) Listeners() []Listener { - return sw.listeners -} - -// Not goroutine safe. -func (sw *Switch) IsListening() bool { - return len(sw.listeners) > 0 -} - -// Not goroutine safe. -func (sw *Switch) SetNodeInfo(nodeInfo *types.NodeInfo) { - sw.nodeInfo = nodeInfo -} - -// Not goroutine safe. -func (sw *Switch) NodeInfo() *types.NodeInfo { - return sw.nodeInfo -} - -// Not goroutine safe. -// NOTE: Overwrites sw.nodeInfo.PubKey -func (sw *Switch) SetNodePrivKey(nodePrivKey acm.PrivKeyEd25519) { - sw.nodePrivKey = nodePrivKey - if sw.nodeInfo != nil { - sw.nodeInfo.PubKey = nodePrivKey.PubKey().(acm.PubKeyEd25519) - } -} - -// Switch.Start() starts all the reactors, peers, and listeners. -func (sw *Switch) OnStart() error { - sw.BaseService.OnStart() - // Start reactors - for _, reactor := range sw.reactors { - _, err := reactor.Start() - if err != nil { - return err - } - } - // Start peers - for _, peer := range sw.peers.List() { - sw.startInitPeer(peer) - } - // Start listeners - for _, listener := range sw.listeners { - go sw.listenerRoutine(listener) - } - return nil -} - -func (sw *Switch) OnStop() { - sw.BaseService.OnStop() - // Stop listeners - for _, listener := range sw.listeners { - listener.Stop() - } - sw.listeners = nil - // Stop peers - for _, peer := range sw.peers.List() { - peer.Stop() - } - sw.peers = NewPeerSet() - // Stop reactors - for _, reactor := range sw.reactors { - reactor.Stop() - } -} - -// NOTE: This performs a blocking handshake before the peer is added. -// CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. -func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { - // Set deadline for handshake so we don't block forever on conn.ReadFull - conn.SetDeadline(time.Now().Add(handshakeTimeoutSeconds * time.Second)) - - // First, encrypt the connection. - sconn, err := MakeSecretConnection(conn, sw.nodePrivKey) - if err != nil { - conn.Close() - return nil, err - } - // Then, perform node handshake - peerNodeInfo, err := peerHandshake(sconn, sw.nodeInfo) - if err != nil { - sconn.Close() - return nil, err - } - // Check that the professed PubKey matches the sconn's. - if !peerNodeInfo.PubKey.Equals(sconn.RemotePubKey()) { - sconn.Close() - return nil, fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", - peerNodeInfo.PubKey, sconn.RemotePubKey()) - } - // Avoid self - if peerNodeInfo.PubKey.Equals(sw.nodeInfo.PubKey) { - sconn.Close() - return nil, fmt.Errorf("Ignoring connection from self") - } - // Check version, chain id - if err := sw.nodeInfo.CompatibleWith(peerNodeInfo); err != nil { - sconn.Close() - return nil, err - } - - // The peerNodeInfo is not verified, so overwrite - // the IP, and the port too if we dialed out - // Everything else we just have to trust - ip, port, _ := net.SplitHostPort(sconn.RemoteAddr().String()) - peerNodeInfo.Host = ip - if outbound { - porti, _ := strconv.Atoi(port) - peerNodeInfo.P2PPort = uint16(porti) - } - peer := newPeer(sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError) - - // Add the peer to .peers - // ignore if duplicate or if we already have too many for that IP range - if err := sw.peers.Add(peer); err != nil { - log.Notice("Ignoring peer", "error", err, "peer", peer) - peer.Stop() - return nil, err - } - - // remove deadline and start peer - conn.SetDeadline(time.Time{}) - if sw.IsRunning() { - sw.startInitPeer(peer) - } - - log.Notice("Added peer", "peer", peer) - return peer, nil -} - -func (sw *Switch) startInitPeer(peer *Peer) { - peer.Start() // spawn send/recv routines - sw.addPeerToReactors(peer) // run AddPeer on each reactor -} - -func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) { - log.Info("Dialing address", "address", addr) - sw.dialing.Set(addr.IP.String(), addr) - conn, err := addr.DialTimeout(peerDialTimeoutSeconds * time.Second) - sw.dialing.Delete(addr.IP.String()) - if err != nil { - log.Info("Failed dialing address", "address", addr, "error", err) - return nil, err - } - peer, err := sw.AddPeerWithConnection(conn, true) - if err != nil { - log.Info("Failed adding peer", "address", addr, "conn", conn, "error", err) - return nil, err - } - log.Notice("Dialed and added peer", "address", addr, "peer", peer) - return peer, nil -} - -func (sw *Switch) IsDialing(addr *NetAddress) bool { - return sw.dialing.Has(addr.IP.String()) -} - -// Broadcast runs a go routine for each attempted send, which will block -// trying to send for defaultSendTimeoutSeconds. Returns a channel -// which receives success values for each attempted send (false if times out) -func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool { - successChan := make(chan bool, len(sw.peers.List())) - log.Info("Broadcast", "channel", chID, "msg", msg) - for _, peer := range sw.peers.List() { - go func(peer *Peer) { - success := peer.Send(chID, msg) - successChan <- success - }(peer) - } - return successChan -} - -// Returns the count of outbound/inbound and outbound-dialing peers. -func (sw *Switch) NumPeers() (outbound, inbound, dialing int) { - peers := sw.peers.List() - for _, peer := range peers { - if peer.outbound { - outbound++ - } else { - inbound++ - } - } - dialing = sw.dialing.Size() - return -} - -func (sw *Switch) Peers() IPeerSet { - return sw.peers -} - -// Disconnect from a peer due to external error. -// TODO: make record depending on reason. -func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) { - log.Notice("Stopping peer for error", "peer", peer, "error", reason) - sw.peers.Remove(peer) - peer.Stop() - sw.removePeerFromReactors(peer, reason) -} - -// Disconnect from a peer gracefully. -// TODO: handle graceful disconnects. -func (sw *Switch) StopPeerGracefully(peer *Peer) { - log.Notice("Stopping peer gracefully") - sw.peers.Remove(peer) - peer.Stop() - sw.removePeerFromReactors(peer, nil) -} - -func (sw *Switch) addPeerToReactors(peer *Peer) { - for _, reactor := range sw.reactors { - reactor.AddPeer(peer) - } -} - -func (sw *Switch) removePeerFromReactors(peer *Peer, reason interface{}) { - for _, reactor := range sw.reactors { - reactor.RemovePeer(peer, reason) - } -} - -func (sw *Switch) listenerRoutine(l Listener) { - for { - inConn, ok := <-l.Connections() - if !ok { - break - } - - // ignore connection if we already have enough - if maxNumPeers <= sw.peers.Size() { - log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxNumPeers) - continue - } - - // Ignore connections from IP ranges for which we have too many - if sw.peers.HasMaxForIPRange(inConn) { - log.Info("Ignoring inbound connection: already have enough peers for that IP range", "address", inConn.RemoteAddr().String()) - continue - } - - // New inbound connection! - _, err := sw.AddPeerWithConnection(inConn, false) - if err != nil { - log.Notice("Ignoring inbound connection: error on AddPeerWithConnection", "address", inConn.RemoteAddr().String(), "error", err) - continue - } - - // NOTE: We don't yet have the listening port of the - // remote (if they have a listener at all). - // The peerHandshake will handle that - } - - // cleanup -} - -//----------------------------------------------------------------------------- - -type SwitchEventNewPeer struct { - Peer *Peer -} - -type SwitchEventDonePeer struct { - Peer *Peer - Error interface{} -} diff --git a/p2p/switch_test.go b/p2p/switch_test.go deleted file mode 100644 index ac4d35cf..00000000 --- a/p2p/switch_test.go +++ /dev/null @@ -1,236 +0,0 @@ -package p2p - -import ( - "bytes" - "sync" - "testing" - "time" - - acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - _ "github.com/tendermint/tendermint/config/tendermint_test" - "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" -) - -type PeerMessage struct { - PeerKey string - Bytes []byte - Counter int -} - -type TestReactor struct { - BaseReactor - - mtx sync.Mutex - channels []*ChannelDescriptor - peersAdded []*Peer - peersRemoved []*Peer - logMessages bool - msgsCounter int - msgsReceived map[byte][]PeerMessage -} - -func NewTestReactor(channels []*ChannelDescriptor, logMessages bool) *TestReactor { - tr := &TestReactor{ - channels: channels, - logMessages: logMessages, - msgsReceived: make(map[byte][]PeerMessage), - } - tr.BaseReactor = *NewBaseReactor(log, "TestReactor", tr) - return tr -} - -func (tr *TestReactor) GetChannels() []*ChannelDescriptor { - return tr.channels -} - -func (tr *TestReactor) AddPeer(peer *Peer) { - tr.mtx.Lock() - defer tr.mtx.Unlock() - tr.peersAdded = append(tr.peersAdded, peer) -} - -func (tr *TestReactor) RemovePeer(peer *Peer, reason interface{}) { - tr.mtx.Lock() - defer tr.mtx.Unlock() - tr.peersRemoved = append(tr.peersRemoved, peer) -} - -func (tr *TestReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { - if tr.logMessages { - tr.mtx.Lock() - defer tr.mtx.Unlock() - //fmt.Printf("Received: %X, %X\n", chID, msgBytes) - tr.msgsReceived[chID] = append(tr.msgsReceived[chID], PeerMessage{peer.Key, msgBytes, tr.msgsCounter}) - tr.msgsCounter++ - } -} - -//----------------------------------------------------------------------------- - -// convenience method for creating two switches connected to each other. -func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *Switch) { - - s1PrivKey := acm.GenPrivKeyEd25519() - s2PrivKey := acm.GenPrivKeyEd25519() - - // Create two switches that will be interconnected. - s1 := initSwitch(NewSwitch()) - s1.SetNodeInfo(&types.NodeInfo{ - PubKey: s1PrivKey.PubKey().(acm.PubKeyEd25519), - Moniker: "switch1", - ChainID: "testing", - Version: types.Versions{Tendermint: "123.123.123"}, - }) - s1.SetNodePrivKey(s1PrivKey) - s2 := initSwitch(NewSwitch()) - s2.SetNodeInfo(&types.NodeInfo{ - PubKey: s2PrivKey.PubKey().(acm.PubKeyEd25519), - Moniker: "switch2", - ChainID: "testing", - Version: types.Versions{Tendermint: "123.123.123"}, - }) - s2.SetNodePrivKey(s2PrivKey) - - // Start switches and reactors - s1.Start() - s2.Start() - - // Create a listener for s1 - l := NewDefaultListener("tcp", ":8001") - - // Dial the listener & add the connection to s2. - lAddr := l.ExternalAddress() - connOut, err := lAddr.Dial() - if err != nil { - t.Fatalf("Could not connect to listener address %v", lAddr) - } else { - t.Logf("Created a connection to listener address %v", lAddr) - } - connIn, ok := <-l.Connections() - if !ok { - t.Fatalf("Could not get inbound connection from listener") - } - - go s1.AddPeerWithConnection(connIn, false) // AddPeer is blocking, requires handshake. - s2.AddPeerWithConnection(connOut, true) - - // Wait for things to happen, peers to get added... - time.Sleep(100 * time.Millisecond) - - // Close the server, no longer needed. - l.Stop() - - return s1, s2 -} - -func TestSwitches(t *testing.T) { - s1, s2 := makeSwitchPair(t, func(sw *Switch) *Switch { - // Make two reactors of two channels each - sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{ID: byte(0x00), Priority: 10}, - &ChannelDescriptor{ID: byte(0x01), Priority: 10}, - }, true)) - sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{ID: byte(0x02), Priority: 10}, - &ChannelDescriptor{ID: byte(0x03), Priority: 10}, - }, true)) - return sw - }) - defer s1.Stop() - defer s2.Stop() - - // Lets send a message from s1 to s2. - if s1.Peers().Size() != 1 { - t.Errorf("Expected exactly 1 peer in s1, got %v", s1.Peers().Size()) - } - if s2.Peers().Size() != 1 { - t.Errorf("Expected exactly 1 peer in s2, got %v", s2.Peers().Size()) - } - - ch0Msg := "channel zero" - ch1Msg := "channel foo" - ch2Msg := "channel bar" - - s1.Broadcast(byte(0x00), ch0Msg) - s1.Broadcast(byte(0x01), ch1Msg) - s1.Broadcast(byte(0x02), ch2Msg) - - // Wait for things to settle... - time.Sleep(5000 * time.Millisecond) - - // Check message on ch0 - ch0Msgs := s2.Reactor("foo").(*TestReactor).msgsReceived[byte(0x00)] - if len(ch0Msgs) != 1 { - t.Errorf("Expected to have received 1 message in ch0") - } - if !bytes.Equal(ch0Msgs[0].Bytes, wire.BinaryBytes(ch0Msg)) { - t.Errorf("Unexpected message bytes. Wanted: %X, Got: %X", wire.BinaryBytes(ch0Msg), ch0Msgs[0].Bytes) - } - - // Check message on ch1 - ch1Msgs := s2.Reactor("foo").(*TestReactor).msgsReceived[byte(0x01)] - if len(ch1Msgs) != 1 { - t.Errorf("Expected to have received 1 message in ch1") - } - if !bytes.Equal(ch1Msgs[0].Bytes, wire.BinaryBytes(ch1Msg)) { - t.Errorf("Unexpected message bytes. Wanted: %X, Got: %X", wire.BinaryBytes(ch1Msg), ch1Msgs[0].Bytes) - } - - // Check message on ch2 - ch2Msgs := s2.Reactor("bar").(*TestReactor).msgsReceived[byte(0x02)] - if len(ch2Msgs) != 1 { - t.Errorf("Expected to have received 1 message in ch2") - } - if !bytes.Equal(ch2Msgs[0].Bytes, wire.BinaryBytes(ch2Msg)) { - t.Errorf("Unexpected message bytes. Wanted: %X, Got: %X", wire.BinaryBytes(ch2Msg), ch2Msgs[0].Bytes) - } - -} - -func BenchmarkSwitches(b *testing.B) { - - b.StopTimer() - - s1, s2 := makeSwitchPair(b, func(sw *Switch) *Switch { - // Make bar reactors of bar channels each - sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{ID: byte(0x00), Priority: 10}, - &ChannelDescriptor{ID: byte(0x01), Priority: 10}, - }, false)) - sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{ID: byte(0x02), Priority: 10}, - &ChannelDescriptor{ID: byte(0x03), Priority: 10}, - }, false)) - return sw - }) - defer s1.Stop() - defer s2.Stop() - - // Allow time for goroutines to boot up - time.Sleep(1000 * time.Millisecond) - b.StartTimer() - - numSuccess, numFailure := 0, 0 - - // Send random message from foo channel to another - for i := 0; i < b.N; i++ { - chID := byte(i % 4) - successChan := s1.Broadcast(chID, "test data") - for s := range successChan { - if s { - numSuccess += 1 - } else { - numFailure += 1 - } - } - } - - log.Warn(Fmt("success: %v, failure: %v", numSuccess, numFailure)) - - // Allow everything to flush before stopping switches & closing connections. - b.StopTimer() - time.Sleep(1000 * time.Millisecond) - -} diff --git a/p2p/upnp/README.md b/p2p/upnp/README.md deleted file mode 100644 index 557d05bd..00000000 --- a/p2p/upnp/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# `tendermint/p2p/upnp` - -## Resources - -* http://www.upnp-hacks.org/upnp.html diff --git a/p2p/upnp/log.go b/p2p/upnp/log.go deleted file mode 100644 index 49f53c86..00000000 --- a/p2p/upnp/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package upnp - -import ( - "github.com/tendermint/tendermint/logger" -) - -var log = logger.New("module", "upnp") diff --git a/p2p/upnp/probe.go b/p2p/upnp/probe.go deleted file mode 100644 index 3f9f8ad9..00000000 --- a/p2p/upnp/probe.go +++ /dev/null @@ -1,111 +0,0 @@ -package upnp - -import ( - "errors" - "fmt" - "net" - "time" - - . "github.com/tendermint/tendermint/common" -) - -type UPNPCapabilities struct { - PortMapping bool - Hairpin bool -} - -func makeUPNPListener(intPort int, extPort int) (NAT, net.Listener, net.IP, error) { - nat, err := Discover() - if err != nil { - return nil, nil, nil, errors.New(fmt.Sprintf("NAT upnp could not be discovered: %v", err)) - } - log.Info(Fmt("ourIP: %v", nat.(*upnpNAT).ourIP)) - - ext, err := nat.GetExternalAddress() - if err != nil { - return nat, nil, nil, errors.New(fmt.Sprintf("External address error: %v", err)) - } - log.Info(Fmt("External address: %v", ext)) - - port, err := nat.AddPortMapping("tcp", extPort, intPort, "Tendermint UPnP Probe", 0) - if err != nil { - return nat, nil, ext, errors.New(fmt.Sprintf("Port mapping error: %v", err)) - } - log.Info(Fmt("Port mapping mapped: %v", port)) - - // also run the listener, open for all remote addresses. - listener, err := net.Listen("tcp", fmt.Sprintf(":%v", intPort)) - if err != nil { - return nat, nil, ext, errors.New(fmt.Sprintf("Error establishing listener: %v", err)) - } - return nat, listener, ext, nil -} - -func testHairpin(listener net.Listener, extAddr string) (supportsHairpin bool) { - // Listener - go func() { - inConn, err := listener.Accept() - if err != nil { - log.Notice(Fmt("Listener.Accept() error: %v", err)) - return - } - log.Info(Fmt("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) - buf := make([]byte, 1024) - n, err := inConn.Read(buf) - if err != nil { - log.Notice(Fmt("Incoming connection read error: %v", err)) - return - } - log.Info(Fmt("Incoming connection read %v bytes: %X", n, buf)) - if string(buf) == "test data" { - supportsHairpin = true - return - } - }() - - // Establish outgoing - outConn, err := net.Dial("tcp", extAddr) - if err != nil { - log.Notice(Fmt("Outgoing connection dial error: %v", err)) - return - } - - n, err := outConn.Write([]byte("test data")) - if err != nil { - log.Notice(Fmt("Outgoing connection write error: %v", err)) - return - } - log.Info(Fmt("Outgoing connection wrote %v bytes", n)) - - // Wait for data receipt - time.Sleep(1 * time.Second) - return -} - -func Probe() (caps UPNPCapabilities, err error) { - log.Info("Probing for UPnP!") - - intPort, extPort := 8001, 8001 - - nat, listener, ext, err := makeUPNPListener(intPort, extPort) - if err != nil { - return - } - caps.PortMapping = true - - // Deferred cleanup - defer func() { - err = nat.DeletePortMapping("tcp", intPort, extPort) - if err != nil { - log.Warn(Fmt("Port mapping delete error: %v", err)) - } - listener.Close() - }() - - supportsHairpin := testHairpin(listener, fmt.Sprintf("%v:%v", ext, extPort)) - if supportsHairpin { - caps.Hairpin = true - } - - return -} diff --git a/p2p/upnp/upnp.go b/p2p/upnp/upnp.go deleted file mode 100644 index 3d6c5503..00000000 --- a/p2p/upnp/upnp.go +++ /dev/null @@ -1,380 +0,0 @@ -/* -Taken from taipei-torrent - -Just enough UPnP to be able to forward ports -*/ -package upnp - -// BUG(jae): TODO: use syscalls to get actual ourIP. http://pastebin.com/9exZG4rh - -import ( - "bytes" - "encoding/xml" - "errors" - "io/ioutil" - "net" - "net/http" - "strconv" - "strings" - "time" -) - -type upnpNAT struct { - serviceURL string - ourIP string - urnDomain string -} - -// protocol is either "udp" or "tcp" -type NAT interface { - GetExternalAddress() (addr net.IP, err error) - AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) - DeletePortMapping(protocol string, externalPort, internalPort int) (err error) -} - -func Discover() (nat NAT, err error) { - ssdp, err := net.ResolveUDPAddr("udp4", "239.255.255.250:1900") - if err != nil { - return - } - conn, err := net.ListenPacket("udp4", ":0") - if err != nil { - return - } - socket := conn.(*net.UDPConn) - defer socket.Close() - - err = socket.SetDeadline(time.Now().Add(3 * time.Second)) - if err != nil { - return - } - - st := "InternetGatewayDevice:1" - - buf := bytes.NewBufferString( - "M-SEARCH * HTTP/1.1\r\n" + - "HOST: 239.255.255.250:1900\r\n" + - "ST: ssdp:all\r\n" + - "MAN: \"ssdp:discover\"\r\n" + - "MX: 2\r\n\r\n") - message := buf.Bytes() - answerBytes := make([]byte, 1024) - for i := 0; i < 3; i++ { - _, err = socket.WriteToUDP(message, ssdp) - if err != nil { - return - } - var n int - n, _, err = socket.ReadFromUDP(answerBytes) - for { - n, _, err = socket.ReadFromUDP(answerBytes) - if err != nil { - break - } - answer := string(answerBytes[0:n]) - if strings.Index(answer, st) < 0 { - continue - } - // HTTP header field names are case-insensitive. - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 - locString := "\r\nlocation:" - answer = strings.ToLower(answer) - locIndex := strings.Index(answer, locString) - if locIndex < 0 { - continue - } - loc := answer[locIndex+len(locString):] - endIndex := strings.Index(loc, "\r\n") - if endIndex < 0 { - continue - } - locURL := strings.TrimSpace(loc[0:endIndex]) - var serviceURL, urnDomain string - serviceURL, urnDomain, err = getServiceURL(locURL) - if err != nil { - return - } - var ourIP net.IP - ourIP, err = localIPv4() - if err != nil { - return - } - nat = &upnpNAT{serviceURL: serviceURL, ourIP: ourIP.String(), urnDomain: urnDomain} - return - } - } - err = errors.New("UPnP port discovery failed.") - return -} - -type Envelope struct { - XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` - Soap *SoapBody -} -type SoapBody struct { - XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"` - ExternalIP *ExternalIPAddressResponse -} - -type ExternalIPAddressResponse struct { - XMLName xml.Name `xml:"GetExternalIPAddressResponse"` - IPAddress string `xml:"NewExternalIPAddress"` -} - -type ExternalIPAddress struct { - XMLName xml.Name `xml:"NewExternalIPAddress"` - IP string -} - -type UPNPService struct { - ServiceType string `xml:"serviceType"` - ControlURL string `xml:"controlURL"` -} - -type DeviceList struct { - Device []Device `xml:"device"` -} - -type ServiceList struct { - Service []UPNPService `xml:"service"` -} - -type Device struct { - XMLName xml.Name `xml:"device"` - DeviceType string `xml:"deviceType"` - DeviceList DeviceList `xml:"deviceList"` - ServiceList ServiceList `xml:"serviceList"` -} - -type Root struct { - Device Device -} - -func getChildDevice(d *Device, deviceType string) *Device { - dl := d.DeviceList.Device - for i := 0; i < len(dl); i++ { - if strings.Index(dl[i].DeviceType, deviceType) >= 0 { - return &dl[i] - } - } - return nil -} - -func getChildService(d *Device, serviceType string) *UPNPService { - sl := d.ServiceList.Service - for i := 0; i < len(sl); i++ { - if strings.Index(sl[i].ServiceType, serviceType) >= 0 { - return &sl[i] - } - } - return nil -} - -func localIPv4() (net.IP, error) { - tt, err := net.Interfaces() - if err != nil { - return nil, err - } - for _, t := range tt { - aa, err := t.Addrs() - if err != nil { - return nil, err - } - for _, a := range aa { - ipnet, ok := a.(*net.IPNet) - if !ok { - continue - } - v4 := ipnet.IP.To4() - if v4 == nil || v4[0] == 127 { // loopback address - continue - } - return v4, nil - } - } - return nil, errors.New("cannot find local IP address") -} - -func getServiceURL(rootURL string) (url, urnDomain string, err error) { - r, err := http.Get(rootURL) - if err != nil { - return - } - defer r.Body.Close() - if r.StatusCode >= 400 { - err = errors.New(string(r.StatusCode)) - return - } - var root Root - err = xml.NewDecoder(r.Body).Decode(&root) - if err != nil { - return - } - a := &root.Device - if strings.Index(a.DeviceType, "InternetGatewayDevice:1") < 0 { - err = errors.New("No InternetGatewayDevice") - return - } - b := getChildDevice(a, "WANDevice:1") - if b == nil { - err = errors.New("No WANDevice") - return - } - c := getChildDevice(b, "WANConnectionDevice:1") - if c == nil { - err = errors.New("No WANConnectionDevice") - return - } - d := getChildService(c, "WANIPConnection:1") - if d == nil { - // Some routers don't follow the UPnP spec, and put WanIPConnection under WanDevice, - // instead of under WanConnectionDevice - d = getChildService(b, "WANIPConnection:1") - - if d == nil { - err = errors.New("No WANIPConnection") - return - } - } - // Extract the domain name, which isn't always 'schemas-upnp-org' - urnDomain = strings.Split(d.ServiceType, ":")[1] - url = combineURL(rootURL, d.ControlURL) - return -} - -func combineURL(rootURL, subURL string) string { - protocolEnd := "://" - protoEndIndex := strings.Index(rootURL, protocolEnd) - a := rootURL[protoEndIndex+len(protocolEnd):] - rootIndex := strings.Index(a, "/") - return rootURL[0:protoEndIndex+len(protocolEnd)+rootIndex] + subURL -} - -func soapRequest(url, function, message, domain string) (r *http.Response, err error) { - fullMessage := "" + - "\r\n" + - "" + message + "" - - req, err := http.NewRequest("POST", url, strings.NewReader(fullMessage)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"") - req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3") - //req.Header.Set("Transfer-Encoding", "chunked") - req.Header.Set("SOAPAction", "\"urn:"+domain+":service:WANIPConnection:1#"+function+"\"") - req.Header.Set("Connection", "Close") - req.Header.Set("Cache-Control", "no-cache") - req.Header.Set("Pragma", "no-cache") - - // log.Stderr("soapRequest ", req) - - r, err = http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - /*if r.Body != nil { - defer r.Body.Close() - }*/ - - if r.StatusCode >= 400 { - // log.Stderr(function, r.StatusCode) - err = errors.New("Error " + strconv.Itoa(r.StatusCode) + " for " + function) - r = nil - return - } - return -} - -type statusInfo struct { - externalIpAddress string -} - -func (n *upnpNAT) getExternalIPAddress() (info statusInfo, err error) { - - message := "\r\n" + - "" - - var response *http.Response - response, err = soapRequest(n.serviceURL, "GetExternalIPAddress", message, n.urnDomain) - if response != nil { - defer response.Body.Close() - } - if err != nil { - return - } - var envelope Envelope - data, err := ioutil.ReadAll(response.Body) - reader := bytes.NewReader(data) - xml.NewDecoder(reader).Decode(&envelope) - - info = statusInfo{envelope.Soap.ExternalIP.IPAddress} - - if err != nil { - return - } - - return -} - -func (n *upnpNAT) GetExternalAddress() (addr net.IP, err error) { - info, err := n.getExternalIPAddress() - if err != nil { - return - } - addr = net.ParseIP(info.externalIpAddress) - return -} - -func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) { - // A single concatenation would break ARM compilation. - message := "\r\n" + - "" + strconv.Itoa(externalPort) - message += "" + protocol + "" - message += "" + strconv.Itoa(internalPort) + "" + - "" + n.ourIP + "" + - "1" - message += description + - "" + strconv.Itoa(timeout) + - "" - - var response *http.Response - response, err = soapRequest(n.serviceURL, "AddPortMapping", message, n.urnDomain) - if response != nil { - defer response.Body.Close() - } - if err != nil { - return - } - - // TODO: check response to see if the port was forwarded - // log.Println(message, response) - // JAE: - // body, err := ioutil.ReadAll(response.Body) - // fmt.Println(string(body), err) - mappedExternalPort = externalPort - _ = response - return -} - -func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) { - - message := "\r\n" + - "" + strconv.Itoa(externalPort) + - "" + protocol + "" + - "" - - var response *http.Response - response, err = soapRequest(n.serviceURL, "DeletePortMapping", message, n.urnDomain) - if response != nil { - defer response.Body.Close() - } - if err != nil { - return - } - - // TODO: check response to see if the port was deleted - // log.Println(message, response) - _ = response - return -} diff --git a/p2p/util.go b/p2p/util.go deleted file mode 100644 index 2be32026..00000000 --- a/p2p/util.go +++ /dev/null @@ -1,15 +0,0 @@ -package p2p - -import ( - "crypto/sha256" -) - -// doubleSha256 calculates sha256(sha256(b)) and returns the resulting bytes. -func doubleSha256(b []byte) []byte { - hasher := sha256.New() - hasher.Write(b) - sum := hasher.Sum(nil) - hasher.Reset() - hasher.Write(sum) - return hasher.Sum(nil) -} diff --git a/p2p/version.go b/p2p/version.go deleted file mode 100644 index 7e51463d..00000000 --- a/p2p/version.go +++ /dev/null @@ -1,3 +0,0 @@ -package p2p - -const Version = "0.3.0" diff --git a/permission/types/permissions.go b/permission/types/permissions.go index 74242ae4..3c43ed17 100644 --- a/permission/types/permissions.go +++ b/permission/types/permissions.go @@ -2,7 +2,7 @@ package types import ( "fmt" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ) //------------------------------------------------------------------------------------------------ diff --git a/permission/types/snatives.go b/permission/types/snatives.go index 3fad9bd8..57315ac9 100644 --- a/permission/types/snatives.go +++ b/permission/types/snatives.go @@ -1,7 +1,7 @@ package types import ( - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) //--------------------------------------------------------------------------------------------------- diff --git a/rpc/client/client.go b/rpc/client/client.go index 3b138c5b..a19fdedf 100644 --- a/rpc/client/client.go +++ b/rpc/client/client.go @@ -7,9 +7,9 @@ import ( "io/ioutil" "net/http" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" . "github.com/tendermint/tendermint/rpc/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func Call(remote string, method string, params []interface{}, dest interface{}) (interface{}, error) { diff --git a/rpc/client/log.go b/rpc/client/log.go index 55476010..465a5c44 100644 --- a/rpc/client/log.go +++ b/rpc/client/log.go @@ -1,7 +1,8 @@ + package rpcclient import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" + "github.com/tendermint/log15" ) var log = log15.New("module", "rpcclient") diff --git a/rpc/core/accounts.go b/rpc/core/accounts.go index 47dc8889..6f165e76 100644 --- a/rpc/core/accounts.go +++ b/rpc/core/accounts.go @@ -3,7 +3,7 @@ package core import ( "fmt" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ctypes "github.com/tendermint/tendermint/rpc/core/types" ) diff --git a/rpc/core/blocks.go b/rpc/core/blocks.go index 427390a2..a04de832 100644 --- a/rpc/core/blocks.go +++ b/rpc/core/blocks.go @@ -2,7 +2,7 @@ package core import ( "fmt" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/core/config.go b/rpc/core/config.go index c2593d5b..7f51b666 100644 --- a/rpc/core/config.go +++ b/rpc/core/config.go @@ -1,7 +1,7 @@ package core import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/rpc/core/consensus.go b/rpc/core/consensus.go index 18e0d39a..a397499a 100644 --- a/rpc/core/consensus.go +++ b/rpc/core/consensus.go @@ -4,7 +4,7 @@ import ( cm "github.com/tendermint/tendermint/consensus" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func ListValidators() (*ctypes.ResultListValidators, error) { diff --git a/rpc/core/log.go b/rpc/core/log.go index 1b4c68f8..d359bee2 100644 --- a/rpc/core/log.go +++ b/rpc/core/log.go @@ -1,7 +1,7 @@ package core import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" + "github.com/tendermint/log15" ) var log = log15.New("module", "rpc") diff --git a/rpc/core/net.go b/rpc/core/net.go index 7ce50312..3dd9118e 100644 --- a/rpc/core/net.go +++ b/rpc/core/net.go @@ -1,7 +1,7 @@ package core import ( - dbm "github.com/tendermint/tendermint/db" + dbm "github.com/tendermint/go-db" ctypes "github.com/tendermint/tendermint/rpc/core/types" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" diff --git a/rpc/core/pipe.go b/rpc/core/pipe.go index 1cad8013..f1797989 100644 --- a/rpc/core/pipe.go +++ b/rpc/core/pipe.go @@ -4,7 +4,7 @@ import ( bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/consensus" mempl "github.com/tendermint/tendermint/mempool" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" stypes "github.com/tendermint/tendermint/state/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/core/txs.go b/rpc/core/txs.go index 073b6665..083a3ad0 100644 --- a/rpc/core/txs.go +++ b/rpc/core/txs.go @@ -3,7 +3,7 @@ package core import ( "fmt" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 21b3b11a..b9efb5f0 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -4,7 +4,7 @@ import ( acm "github.com/tendermint/tendermint/account" stypes "github.com/tendermint/tendermint/state/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) type ResultGetStorage struct { diff --git a/rpc/core_client/client.go b/rpc/core_client/client.go index c2417248..33c11bba 100644 --- a/rpc/core_client/client.go +++ b/rpc/core_client/client.go @@ -5,7 +5,7 @@ import ( "fmt" ctypes "github.com/tendermint/tendermint/rpc/core/types" rpctypes "github.com/tendermint/tendermint/rpc/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" "io/ioutil" "net/http" "net/url" diff --git a/rpc/core_client/log.go b/rpc/core_client/log.go index a3784715..b0fffb7a 100644 --- a/rpc/core_client/log.go +++ b/rpc/core_client/log.go @@ -1,7 +1,8 @@ + package core_client import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" + "github.com/tendermint/log15" ) var log = log15.New("module", "core_client") diff --git a/rpc/core_client/ws_client.go b/rpc/core_client/ws_client.go index 904fbd94..9778477e 100644 --- a/rpc/core_client/ws_client.go +++ b/rpc/core_client/ws_client.go @@ -5,11 +5,11 @@ import ( "strings" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/gorilla/websocket" - . "github.com/tendermint/tendermint/common" + "github.com/gorilla/websocket" + . "github.com/tendermint/go-common" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/rpc/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) const ( diff --git a/rpc/server/handlers.go b/rpc/server/handlers.go index d0400ec1..b764106f 100644 --- a/rpc/server/handlers.go +++ b/rpc/server/handlers.go @@ -1,3 +1,4 @@ + package rpcserver import ( @@ -11,13 +12,13 @@ import ( "sort" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/gorilla/websocket" - . "github.com/tendermint/tendermint/common" + "github.com/gorilla/websocket" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" ctypes "github.com/tendermint/tendermint/rpc/core/types" . "github.com/tendermint/tendermint/rpc/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc) { diff --git a/rpc/server/http_server.go b/rpc/server/http_server.go index 16f6a965..a93e95f7 100644 --- a/rpc/server/http_server.go +++ b/rpc/server/http_server.go @@ -11,9 +11,9 @@ import ( "time" "github.com/tendermint/tendermint/alert" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" . "github.com/tendermint/tendermint/rpc/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, error) { diff --git a/rpc/server/log.go b/rpc/server/log.go index 1b296cdc..704e22e3 100644 --- a/rpc/server/log.go +++ b/rpc/server/log.go @@ -1,7 +1,7 @@ package rpcserver import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" + "github.com/tendermint/log15" ) var log = log15.New("module", "rpcserver") diff --git a/rpc/test/config.go b/rpc/test/config.go index ef5d5433..2fe20981 100644 --- a/rpc/test/config.go +++ b/rpc/test/config.go @@ -1,7 +1,7 @@ package rpctest import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index e49c3f08..5b6da90b 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -6,9 +6,9 @@ import ( "testing" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" nm "github.com/tendermint/tendermint/node" - "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/go-p2p" ctypes "github.com/tendermint/tendermint/rpc/core/types" cclient "github.com/tendermint/tendermint/rpc/core_client" "github.com/tendermint/tendermint/types" diff --git a/rpc/test/tests.go b/rpc/test/tests.go index e684bbef..027e4502 100644 --- a/rpc/test/tests.go +++ b/rpc/test/tests.go @@ -3,7 +3,7 @@ package rpctest import ( "bytes" "fmt" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/types" "testing" ) diff --git a/rpc/test/ws_helpers.go b/rpc/test/ws_helpers.go index 6bf3bab4..0ca30207 100644 --- a/rpc/test/ws_helpers.go +++ b/rpc/test/ws_helpers.go @@ -7,12 +7,12 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/gorilla/websocket" + "github.com/gorilla/websocket" + "github.com/tendermint/go-wire" _ "github.com/tendermint/tendermint/config/tendermint_test" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/rpc/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" ) //-------------------------------------------------------------------------------- diff --git a/scripts/unsafe_upgrade_group.sh b/scripts/unsafe_upgrade_group.sh new file mode 100755 index 00000000..814e6c60 --- /dev/null +++ b/scripts/unsafe_upgrade_group.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -euo pipefail +IFS=$'\n\t' + +printf "Upgrading group $1...\n" +sleep 3 + +debora --group "$1" run -- bash -c "cd \$GOPATH/src/github.com/tendermint/tendermint; git pull origin develop; make" +printf "Done\n" diff --git a/state/block_cache.go b/state/block_cache.go index 0bbab6fa..6f0fb356 100644 --- a/state/block_cache.go +++ b/state/block_cache.go @@ -5,11 +5,11 @@ import ( "sort" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - dbm "github.com/tendermint/tendermint/db" - "github.com/tendermint/tendermint/merkle" + . "github.com/tendermint/go-common" + dbm "github.com/tendermint/go-db" + "github.com/tendermint/go-merkle" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func makeStorage(db dbm.DB, root []byte) merkle.Tree { diff --git a/state/common.go b/state/common.go index 0adad0aa..87b8497a 100644 --- a/state/common.go +++ b/state/common.go @@ -2,7 +2,7 @@ package state import ( acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/vm" ) diff --git a/state/execution.go b/state/execution.go index bdb858ab..a8a04e3d 100644 --- a/state/execution.go +++ b/state/execution.go @@ -6,7 +6,7 @@ import ( "fmt" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" ptypes "github.com/tendermint/tendermint/permission/types" // for GlobalPermissionAddress ... "github.com/tendermint/tendermint/types" diff --git a/state/genesis_test.go b/state/genesis_test.go index dfa66339..251f04df 100644 --- a/state/genesis_test.go +++ b/state/genesis_test.go @@ -6,7 +6,7 @@ import ( "fmt" "testing" - tdb "github.com/tendermint/tendermint/db" + tdb "github.com/tendermint/go-db" ptypes "github.com/tendermint/tendermint/permission/types" . "github.com/tendermint/tendermint/state/types" ) diff --git a/state/log.go b/state/log.go index 7f1d3eba..5b102b57 100644 --- a/state/log.go +++ b/state/log.go @@ -1,7 +1,7 @@ package state import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "state") diff --git a/state/permissions_test.go b/state/permissions_test.go index 34dfc9e5..4a9bad09 100644 --- a/state/permissions_test.go +++ b/state/permissions_test.go @@ -8,8 +8,8 @@ import ( "time" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - dbm "github.com/tendermint/tendermint/db" + . "github.com/tendermint/go-common" + dbm "github.com/tendermint/go-db" "github.com/tendermint/tendermint/events" ptypes "github.com/tendermint/tendermint/permission/types" . "github.com/tendermint/tendermint/state/types" diff --git a/state/state.go b/state/state.go index b6189003..3dd2044d 100644 --- a/state/state.go +++ b/state/state.go @@ -1,3 +1,4 @@ + package state import ( @@ -7,14 +8,14 @@ import ( "time" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - dbm "github.com/tendermint/tendermint/db" + . "github.com/tendermint/go-common" + dbm "github.com/tendermint/go-db" "github.com/tendermint/tendermint/events" - "github.com/tendermint/tendermint/merkle" + "github.com/tendermint/go-merkle" ptypes "github.com/tendermint/tendermint/permission/types" . "github.com/tendermint/tendermint/state/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) var ( diff --git a/state/tx_cache.go b/state/tx_cache.go index 8afd1cd0..8330f7b2 100644 --- a/state/tx_cache.go +++ b/state/tx_cache.go @@ -2,7 +2,7 @@ package state import ( acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ptypes "github.com/tendermint/tendermint/permission/types" // for GlobalPermissionAddress ... "github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/vm" diff --git a/state/tx_cache_test.go b/state/tx_cache_test.go index c0985564..85e67f4c 100644 --- a/state/tx_cache_test.go +++ b/state/tx_cache_test.go @@ -5,7 +5,7 @@ import ( "testing" stypes "github.com/tendermint/tendermint/state/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) func TestStateToFromVMAccount(t *testing.T) { diff --git a/state/types/genesis.go b/state/types/genesis.go index e6abb2a6..fe73156b 100644 --- a/state/types/genesis.go +++ b/state/types/genesis.go @@ -5,10 +5,10 @@ import ( "time" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ptypes "github.com/tendermint/tendermint/permission/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) //------------------------------------------------------------ diff --git a/types/block.go b/types/block.go index 718b6a5a..20fc1178 100644 --- a/types/block.go +++ b/types/block.go @@ -8,9 +8,9 @@ import ( "time" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/merkle" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-merkle" + "github.com/tendermint/go-wire" ) type Block struct { diff --git a/types/config.go b/types/config.go index 915778dd..cb982879 100644 --- a/types/config.go +++ b/types/config.go @@ -1,7 +1,7 @@ package types import ( - cfg "github.com/tendermint/tendermint/config" + cfg "github.com/tendermint/go-config" ) var config cfg.Config = nil diff --git a/types/events.go b/types/events.go index 5d717734..be442f8b 100644 --- a/types/events.go +++ b/types/events.go @@ -4,8 +4,8 @@ import ( "fmt" "time" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) // Functions to generate eventId strings diff --git a/types/log.go b/types/log.go index fed0c559..dbe8a678 100644 --- a/types/log.go +++ b/types/log.go @@ -1,7 +1,7 @@ package types import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "types") diff --git a/types/part_set.go b/types/part_set.go index d9c4c5db..53e39848 100644 --- a/types/part_set.go +++ b/types/part_set.go @@ -7,11 +7,11 @@ import ( "io" "sync" - "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" + "code.google.com/p/go.crypto/ripemd160" - "github.com/tendermint/tendermint/wire" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/merkle" + "github.com/tendermint/go-wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-merkle" ) const ( diff --git a/types/part_set_test.go b/types/part_set_test.go index 5d2d9142..0260af7f 100644 --- a/types/part_set_test.go +++ b/types/part_set_test.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "testing" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ) func TestBasicPartSet(t *testing.T) { diff --git a/types/priv_validator.go b/types/priv_validator.go index 0cfb0021..f2a31c10 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -1,3 +1,4 @@ + package types import ( @@ -10,10 +11,10 @@ import ( "sync" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519" + "github.com/tendermint/ed25519" ) const ( diff --git a/types/proposal.go b/types/proposal.go index 78c393f9..5d788e7b 100644 --- a/types/proposal.go +++ b/types/proposal.go @@ -6,8 +6,8 @@ import ( "io" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) var ( diff --git a/types/proposal_test.go b/types/proposal_test.go index f37c11ee..24692c3a 100644 --- a/types/proposal_test.go +++ b/types/proposal_test.go @@ -4,7 +4,7 @@ import ( "testing" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" _ "github.com/tendermint/tendermint/config/tendermint_test" ) diff --git a/types/tx.go b/types/tx.go index 76235d2c..cc7068b8 100644 --- a/types/tx.go +++ b/types/tx.go @@ -5,12 +5,12 @@ import ( "errors" "io" - "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/ripemd160" + "golang.org/x/crypto/ripemd160" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ptypes "github.com/tendermint/tendermint/permission/types" - "github.com/tendermint/tendermint/wire" + "github.com/tendermint/go-wire" ) var ( diff --git a/types/tx_test.go b/types/tx_test.go index 61acab15..ee13d7ba 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -4,7 +4,7 @@ import ( "testing" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" _ "github.com/tendermint/tendermint/config/tendermint_test" ptypes "github.com/tendermint/tendermint/permission/types" ) diff --git a/types/validator.go b/types/validator.go index dbf4cbde..8c364804 100644 --- a/types/validator.go +++ b/types/validator.go @@ -6,8 +6,8 @@ import ( "io" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) // Persistent (mostly) static data for each Validator diff --git a/types/validator_set.go b/types/validator_set.go index 7dc4ee62..f2b35a8f 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -7,8 +7,8 @@ import ( "strings" "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/merkle" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-merkle" ) // ValidatorSet represent a set of *Validator at a given height. diff --git a/types/validator_set_test.go b/types/validator_set_test.go index c8b5d307..eca57d77 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -2,7 +2,7 @@ package types import ( "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "bytes" "strings" diff --git a/types/vote.go b/types/vote.go index c23ca9cb..1c4763e5 100644 --- a/types/vote.go +++ b/types/vote.go @@ -6,8 +6,8 @@ import ( "io" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) var ( diff --git a/types/vote_set.go b/types/vote_set.go index 36942e75..efd59717 100644 --- a/types/vote_set.go +++ b/types/vote_set.go @@ -7,8 +7,8 @@ import ( "sync" acm "github.com/tendermint/tendermint/account" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/wire" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) // VoteSet helps collect signatures from validators at each height+round diff --git a/types/vote_set_test.go b/types/vote_set_test.go index d521478e..c97c640f 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -4,8 +4,8 @@ import ( "bytes" "sort" - . "github.com/tendermint/tendermint/common" - . "github.com/tendermint/tendermint/common/test" + . "github.com/tendermint/go-common" + . "github.com/tendermint/go-common/test" _ "github.com/tendermint/tendermint/config/tendermint_test" "testing" diff --git a/vm/log.go b/vm/log.go index 9862495b..82880ae9 100644 --- a/vm/log.go +++ b/vm/log.go @@ -1,7 +1,7 @@ package vm import ( - "github.com/tendermint/tendermint/logger" + "github.com/tendermint/go-logger" ) var log = logger.New("module", "vm") diff --git a/vm/native.go b/vm/native.go index aac54d9b..50c9c896 100644 --- a/vm/native.go +++ b/vm/native.go @@ -1,9 +1,10 @@ + package vm import ( "crypto/sha256" - "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" - . "github.com/tendermint/tendermint/common" + "code.google.com/p/go.crypto/ripemd160" + . "github.com/tendermint/go-common" ) var registeredNativeContracts = make(map[Word256]NativeContract) diff --git a/vm/opcodes.go b/vm/opcodes.go index 1259cb15..87e09bfd 100644 --- a/vm/opcodes.go +++ b/vm/opcodes.go @@ -2,7 +2,7 @@ package vm import ( "fmt" - "github.com/tendermint/tendermint/Godeps/_workspace/src/gopkg.in/fatih/set.v0" + "gopkg.in/fatih/set.v0" ) type OpCode byte diff --git a/vm/snative.go b/vm/snative.go index 2fd3b0f9..d5a8a519 100644 --- a/vm/snative.go +++ b/vm/snative.go @@ -3,7 +3,7 @@ package vm import ( "fmt" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ptypes "github.com/tendermint/tendermint/permission/types" ) diff --git a/vm/stack.go b/vm/stack.go index 7dae3e71..979aba2e 100644 --- a/vm/stack.go +++ b/vm/stack.go @@ -2,7 +2,7 @@ package vm import ( "fmt" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ) // Not goroutine safe diff --git a/vm/test/fake_app_state.go b/vm/test/fake_app_state.go index 72dcca58..78dc6745 100644 --- a/vm/test/fake_app_state.go +++ b/vm/test/fake_app_state.go @@ -1,7 +1,7 @@ package vm import ( - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" . "github.com/tendermint/tendermint/vm" "github.com/tendermint/tendermint/vm/sha3" ) diff --git a/vm/test/log_event_test.go b/vm/test/log_event_test.go index fa598b00..cd03b714 100644 --- a/vm/test/log_event_test.go +++ b/vm/test/log_event_test.go @@ -5,7 +5,7 @@ import ( "reflect" "testing" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" "github.com/tendermint/tendermint/types" . "github.com/tendermint/tendermint/vm" diff --git a/vm/test/vm_test.go b/vm/test/vm_test.go index dc268a6a..846d9fe9 100644 --- a/vm/test/vm_test.go +++ b/vm/test/vm_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" ptypes "github.com/tendermint/tendermint/permission/types" "github.com/tendermint/tendermint/types" diff --git a/vm/types.go b/vm/types.go index cb9bc64f..65c0724e 100644 --- a/vm/types.go +++ b/vm/types.go @@ -1,7 +1,7 @@ package vm import ( - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" ptypes "github.com/tendermint/tendermint/permission/types" ) diff --git a/vm/vm.go b/vm/vm.go index ac10882e..ca11f934 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -6,7 +6,7 @@ import ( "fmt" "math/big" - . "github.com/tendermint/tendermint/common" + . "github.com/tendermint/go-common" "github.com/tendermint/tendermint/events" ptypes "github.com/tendermint/tendermint/permission/types" "github.com/tendermint/tendermint/types" diff --git a/wire/README.md b/wire/README.md deleted file mode 100644 index 3108505e..00000000 --- a/wire/README.md +++ /dev/null @@ -1,138 +0,0 @@ -### NOTICE - -This documentation is out of date. -* 0x00 is reserved as a nil byte for RegisterInterface -* moved TypeByte() into RegisterInterface/ConcreteType -* Pointers that don't have a declared TypeByte() are - encoded with a leading 0x00 (nil) or 0x01. - -# `tendermint/wire` - -The `binary` submodule encodes primary types and structs into bytes. - -## Primary types - -uint\*, int\*, string, time, byteslice and byteslice-slice types can be -encoded and decoded with the following methods: - -The following writes `o uint64` to `w io.Writer`, and increments `n` and/or sets `err` -```go -WriteUint64(o uint64, w io.Writer, n *int64, err *error) - -// Typical usage: -buf, n, err := new(bytes.Buffer), new(int64), new(error) -WriteUint64(uint64(x), buf, n, err) -if *err != nil { - panic(err) -} - -``` - -The following reads a `uint64` from `r io.Reader`, and increments `n` and/or sets `err` -```go -var o = ReadUint64(r io.Reader, n *int64, err *error) -``` - -Similar methods for `uint32`, `uint16`, `uint8`, `int64`, `int32`, `int16`, `int8` exist. -Protobuf variable length encoding is done with `uint` and `int` types: -```go -WriteUvarint(o uint, w io.Writer, n *int64, err *error) -var o = ReadUvarint(r io.Reader, n *int64, err *error) -``` - -Byteslices can be written with: -```go -WriteByteSlice(bz []byte, w io.Writer, n *int64, err *error) -``` - -Byteslices (and all slices such as byteslice-slices) are prepended with -`uvarint` encoded length, so `ReadByteSlice()` knows how many bytes to read. - -Note that there is no type information encoded -- the caller is assumed to know what types -to decode. - -## Struct Types - -Struct types can be automatically encoded with reflection. Unlike json-encoding, no field -name or type information is encoded. Field values are simply encoded in order. - -```go -type Foo struct { - MyString string - MyUint32 uint32 - myPrivateBytes []byte -} - -foo := Foo{"my string", math.MaxUint32, []byte("my private bytes")} - -buf, n, err := new(bytes.Buffer), new(int64), new(error) -WriteBinary(foo, buf, n, err) - -// fmt.Printf("%X", buf.Bytes()) gives: -// 096D7920737472696E67FFFFFFFF -// 09: uvarint encoded length of string "my string" -// 6D7920737472696E67: bytes of string "my string" -// FFFFFFFF: bytes for MaxUint32 -// Note that the unexported "myPrivateBytes" isn't encoded. - -foo2 := ReadBinary(Foo{}, buf, n, err).(Foo) - -// Or, to decode onto a pointer: -foo2 := ReadBinaryPtr(&Foo{}, buf, n, err).(*Foo) -``` - -WriteBinary and ReadBinary can encode/decode structs recursively. However, interface field -values are a bit more complicated. - -```go -type Greeter interface { - Greet() string -} - -type Dog struct{} -func (d Dog) Greet() string { return "Woof!" } - -type Cat struct{} -func (c Cat) Greet() string { return "Meow!" } - -type Foo struct { - Greeter -} - -foo := Foo{Dog{}} - -buf, n, err := new(bytes.Buffer), new(int64), new(error) -WriteBinary(foo, buf, n, err) - -// This errors because we don't know whether to read a Dog or Cat. -foo2 := ReadBinary(Foo{}, buf, n, err) -``` - -In the above example, `ReadBinary()` fails because the `Greeter` field for `Foo{}` -is ambiguous -- it could be either a `Dog{}` or a `Cat{}`, like a union structure. -The solution is to declare the concrete implementation types for interfaces: - -```go -type Dog struct{} -func (d Dog) TypeByte() byte { return GreeterTypeDog } -func (d Dog) Greet() string { return "Woof!" } - -type Cat struct{} -func (c Cat) TypeByte() byte { return GreeterTypeCat } -func (c Cat) Greet() string { return "Meow!" } - -var _ = RegisterInterface( - struct{Greeter}{}, - ConcreteType{Dog{}}, - ConcreteType{Cat{}}, -}) -``` - -NOTE: The TypeByte() is written and expected to be read even when the struct -is encoded or decoded directly: - -```go -WriteBinary(Dog{}, buf, n, err) // Writes GreeterTypeDog byte -dog_ := ReadBinary(Dog{}, buf, n, err) // Expects to read GreeterTypeDog byte -dog := dog_.(Dog) // ok if *err != nil, otherwise dog_ == nil. -``` diff --git a/wire/byteslice.go b/wire/byteslice.go deleted file mode 100644 index ee4bb941..00000000 --- a/wire/byteslice.go +++ /dev/null @@ -1,68 +0,0 @@ -package wire - -import ( - "io" - - . "github.com/tendermint/tendermint/common" -) - -func WriteByteSlice(bz []byte, w io.Writer, n *int64, err *error) { - WriteVarint(len(bz), w, n, err) - WriteTo(bz, w, n, err) -} - -func ReadByteSlice(r io.Reader, n *int64, err *error) []byte { - length := ReadVarint(r, n, err) - if *err != nil { - return nil - } - if length < 0 { - *err = ErrBinaryReadSizeUnderflow - return nil - } - if MaxBinaryReadSize < MaxInt64(int64(length), *n+int64(length)) { - *err = ErrBinaryReadSizeOverflow - return nil - } - - buf := make([]byte, length) - ReadFull(buf, r, n, err) - return buf -} - -//----------------------------------------------------------------------------- - -func WriteByteSlices(bzz [][]byte, w io.Writer, n *int64, err *error) { - WriteVarint(len(bzz), w, n, err) - for _, bz := range bzz { - WriteByteSlice(bz, w, n, err) - if *err != nil { - return - } - } -} - -func ReadByteSlices(r io.Reader, n *int64, err *error) [][]byte { - length := ReadVarint(r, n, err) - if *err != nil { - return nil - } - if length < 0 { - *err = ErrBinaryReadSizeUnderflow - return nil - } - if MaxBinaryReadSize < MaxInt64(int64(length), *n+int64(length)) { - *err = ErrBinaryReadSizeOverflow - return nil - } - - bzz := make([][]byte, length) - for i := 0; i < length; i++ { - bz := ReadByteSlice(r, n, err) - if *err != nil { - return nil - } - bzz[i] = bz - } - return bzz -} diff --git a/wire/codec.go b/wire/codec.go deleted file mode 100644 index 63edb94a..00000000 --- a/wire/codec.go +++ /dev/null @@ -1,171 +0,0 @@ -package wire - -import ( - "bytes" - "errors" - "fmt" - . "github.com/tendermint/tendermint/common" - "io" - "reflect" - "time" -) - -type Encoder func(o interface{}, w io.Writer, n *int64, err *error) -type Decoder func(r io.Reader, n *int64, err *error) interface{} -type Comparator func(o1 interface{}, o2 interface{}) int - -type Codec struct { - Encode Encoder - Decode Decoder - Compare Comparator -} - -const ( - typeByte = byte(0x01) - typeInt8 = byte(0x02) - // typeUint8 = byte(0x03) - typeInt16 = byte(0x04) - typeUint16 = byte(0x05) - typeInt32 = byte(0x06) - typeUint32 = byte(0x07) - typeInt64 = byte(0x08) - typeUint64 = byte(0x09) - typeVarint = byte(0x0A) - typeUvarint = byte(0x0B) - typeString = byte(0x10) - typeByteSlice = byte(0x11) - typeTime = byte(0x20) -) - -func BasicCodecEncoder(o interface{}, w io.Writer, n *int64, err *error) { - switch o := o.(type) { - case nil: - PanicSanity("nil type unsupported") - case byte: - WriteByte(typeByte, w, n, err) - WriteByte(o, w, n, err) - case int8: - WriteByte(typeInt8, w, n, err) - WriteInt8(o, w, n, err) - //case uint8: - // WriteByte( typeUint8, w, n, err) - // WriteUint8( o, w, n, err) - case int16: - WriteByte(typeInt16, w, n, err) - WriteInt16(o, w, n, err) - case uint16: - WriteByte(typeUint16, w, n, err) - WriteUint16(o, w, n, err) - case int32: - WriteByte(typeInt32, w, n, err) - WriteInt32(o, w, n, err) - case uint32: - WriteByte(typeUint32, w, n, err) - WriteUint32(o, w, n, err) - case int64: - WriteByte(typeInt64, w, n, err) - WriteInt64(o, w, n, err) - case uint64: - WriteByte(typeUint64, w, n, err) - WriteUint64(o, w, n, err) - case int: - WriteByte(typeVarint, w, n, err) - WriteVarint(o, w, n, err) - case uint: - WriteByte(typeUvarint, w, n, err) - WriteUvarint(o, w, n, err) - case string: - WriteByte(typeString, w, n, err) - WriteString(o, w, n, err) - case []byte: - WriteByte(typeByteSlice, w, n, err) - WriteByteSlice(o, w, n, err) - case time.Time: - WriteByte(typeTime, w, n, err) - WriteTime(o, w, n, err) - default: - PanicSanity(fmt.Sprintf("Unsupported type: %v", reflect.TypeOf(o))) - } -} - -func BasicCodecDecoder(r io.Reader, n *int64, err *error) (o interface{}) { - type_ := ReadByte(r, n, err) - if *err != nil { - return - } - switch type_ { - case typeByte: - o = ReadByte(r, n, err) - case typeInt8: - o = ReadInt8(r, n, err) - //case typeUint8: - // o = ReadUint8(r, n, err) - case typeInt16: - o = ReadInt16(r, n, err) - case typeUint16: - o = ReadUint16(r, n, err) - case typeInt32: - o = ReadInt32(r, n, err) - case typeUint32: - o = ReadUint32(r, n, err) - case typeInt64: - o = ReadInt64(r, n, err) - case typeUint64: - o = ReadUint64(r, n, err) - case typeVarint: - o = ReadVarint(r, n, err) - case typeUvarint: - o = ReadUvarint(r, n, err) - case typeString: - o = ReadString(r, n, err) - case typeByteSlice: - o = ReadByteSlice(r, n, err) - case typeTime: - o = ReadTime(r, n, err) - default: - *err = errors.New(Fmt("Unsupported type byte: %X", type_)) - } - return -} - -// Contract: Caller must ensure that types match. -func BasicCodecComparator(o1 interface{}, o2 interface{}) int { - switch o1.(type) { - case byte: - return int(o1.(byte) - o2.(byte)) - case int8: - return int(o1.(int8) - o2.(int8)) - //case uint8: - case int16: - return int(o1.(int16) - o2.(int16)) - case uint16: - return int(o1.(uint16) - o2.(uint16)) - case int32: - return int(o1.(int32) - o2.(int32)) - case uint32: - return int(o1.(uint32) - o2.(uint32)) - case int64: - return int(o1.(int64) - o2.(int64)) - case uint64: - return int(o1.(uint64) - o2.(uint64)) - case int: - return o1.(int) - o2.(int) - case uint: - return int(o1.(uint)) - int(o2.(uint)) - case string: - return bytes.Compare([]byte(o1.(string)), []byte(o2.(string))) - case []byte: - return bytes.Compare(o1.([]byte), o2.([]byte)) - case time.Time: - return int(o1.(time.Time).UnixNano() - o2.(time.Time).UnixNano()) - default: - PanicSanity(Fmt("Unsupported type: %v", reflect.TypeOf(o1))) - } - return 0 -} - -var BasicCodec = Codec{ - Encode: BasicCodecEncoder, - Decode: BasicCodecDecoder, - Compare: BasicCodecComparator, -} diff --git a/wire/int.go b/wire/int.go deleted file mode 100644 index c63666fa..00000000 --- a/wire/int.go +++ /dev/null @@ -1,270 +0,0 @@ -package wire - -import ( - "encoding/binary" - "errors" - "io" -) - -// Byte - -func WriteByte(b byte, w io.Writer, n *int64, err *error) { - WriteTo([]byte{b}, w, n, err) -} - -func ReadByte(r io.Reader, n *int64, err *error) byte { - buf := make([]byte, 1) - ReadFull(buf, r, n, err) - return buf[0] -} - -// Int8 - -func WriteInt8(i int8, w io.Writer, n *int64, err *error) { - WriteByte(byte(i), w, n, err) -} - -func ReadInt8(r io.Reader, n *int64, err *error) int8 { - return int8(ReadByte(r, n, err)) -} - -// Uint8 - -func WriteUint8(i uint8, w io.Writer, n *int64, err *error) { - WriteByte(byte(i), w, n, err) -} - -func ReadUint8(r io.Reader, n *int64, err *error) uint8 { - return uint8(ReadByte(r, n, err)) -} - -// Int16 - -func WriteInt16(i int16, w io.Writer, n *int64, err *error) { - buf := make([]byte, 2) - binary.BigEndian.PutUint16(buf, uint16(i)) - *n += 2 - WriteTo(buf, w, n, err) -} - -func ReadInt16(r io.Reader, n *int64, err *error) int16 { - buf := make([]byte, 2) - ReadFull(buf, r, n, err) - return int16(binary.BigEndian.Uint16(buf)) -} - -// Uint16 - -func WriteUint16(i uint16, w io.Writer, n *int64, err *error) { - buf := make([]byte, 2) - binary.BigEndian.PutUint16(buf, uint16(i)) - *n += 2 - WriteTo(buf, w, n, err) -} - -func ReadUint16(r io.Reader, n *int64, err *error) uint16 { - buf := make([]byte, 2) - ReadFull(buf, r, n, err) - return uint16(binary.BigEndian.Uint16(buf)) -} - -// []Uint16 - -func WriteUint16s(iz []uint16, w io.Writer, n *int64, err *error) { - WriteUint32(uint32(len(iz)), w, n, err) - for _, i := range iz { - WriteUint16(i, w, n, err) - if *err != nil { - return - } - } -} - -func ReadUint16s(r io.Reader, n *int64, err *error) []uint16 { - length := ReadUint32(r, n, err) - if *err != nil { - return nil - } - iz := make([]uint16, length) - for j := uint32(0); j < length; j++ { - ii := ReadUint16(r, n, err) - if *err != nil { - return nil - } - iz[j] = ii - } - return iz -} - -// Int32 - -func WriteInt32(i int32, w io.Writer, n *int64, err *error) { - buf := make([]byte, 4) - binary.BigEndian.PutUint32(buf, uint32(i)) - *n += 4 - WriteTo(buf, w, n, err) -} - -func ReadInt32(r io.Reader, n *int64, err *error) int32 { - buf := make([]byte, 4) - ReadFull(buf, r, n, err) - return int32(binary.BigEndian.Uint32(buf)) -} - -// Uint32 - -func WriteUint32(i uint32, w io.Writer, n *int64, err *error) { - buf := make([]byte, 4) - binary.BigEndian.PutUint32(buf, uint32(i)) - *n += 4 - WriteTo(buf, w, n, err) -} - -func ReadUint32(r io.Reader, n *int64, err *error) uint32 { - buf := make([]byte, 4) - ReadFull(buf, r, n, err) - return uint32(binary.BigEndian.Uint32(buf)) -} - -// Int64 - -func WriteInt64(i int64, w io.Writer, n *int64, err *error) { - buf := make([]byte, 8) - binary.BigEndian.PutUint64(buf, uint64(i)) - *n += 8 - WriteTo(buf, w, n, err) -} - -func ReadInt64(r io.Reader, n *int64, err *error) int64 { - buf := make([]byte, 8) - ReadFull(buf, r, n, err) - return int64(binary.BigEndian.Uint64(buf)) -} - -// Uint64 - -func WriteUint64(i uint64, w io.Writer, n *int64, err *error) { - buf := make([]byte, 8) - binary.BigEndian.PutUint64(buf, uint64(i)) - *n += 8 - WriteTo(buf, w, n, err) -} - -func ReadUint64(r io.Reader, n *int64, err *error) uint64 { - buf := make([]byte, 8) - ReadFull(buf, r, n, err) - return uint64(binary.BigEndian.Uint64(buf)) -} - -// Varint - -func uvarintSize(i uint64) int { - if i == 0 { - return 0 - } - if i < 1<<8 { - return 1 - } - if i < 1<<16 { - return 2 - } - if i < 1<<24 { - return 3 - } - if i < 1<<32 { - return 4 - } - if i < 1<<40 { - return 5 - } - if i < 1<<48 { - return 6 - } - if i < 1<<56 { - return 7 - } - return 8 -} - -func WriteVarint(i int, w io.Writer, n *int64, err *error) { - var negate = false - if i < 0 { - negate = true - i = -i - } - var size = uvarintSize(uint64(i)) - if negate { - // e.g. 0xF1 for a single negative byte - WriteUint8(uint8(size+0xF0), w, n, err) - } else { - WriteUint8(uint8(size), w, n, err) - } - if size > 0 { - buf := make([]byte, 8) - binary.BigEndian.PutUint64(buf, uint64(i)) - WriteTo(buf[(8-size):], w, n, err) - } - *n += int64(1 + size) -} - -func ReadVarint(r io.Reader, n *int64, err *error) int { - var size = ReadUint8(r, n, err) - var negate = false - if (size >> 4) == 0xF { - negate = true - size = size & 0x0F - } - if size > 8 { - setFirstErr(err, errors.New("Varint overflow")) - return 0 - } - if size == 0 { - if negate { - setFirstErr(err, errors.New("Varint does not allow negative zero")) - } - return 0 - } - buf := make([]byte, 8) - ReadFull(buf[(8-size):], r, n, err) - *n += int64(1 + size) - var i = int(binary.BigEndian.Uint64(buf)) - if negate { - return -i - } else { - return i - } -} - -// Uvarint - -func WriteUvarint(i uint, w io.Writer, n *int64, err *error) { - var size = uvarintSize(uint64(i)) - WriteUint8(uint8(size), w, n, err) - if size > 0 { - buf := make([]byte, 8) - binary.BigEndian.PutUint64(buf, uint64(i)) - WriteTo(buf[(8-size):], w, n, err) - } - *n += int64(1 + size) -} - -func ReadUvarint(r io.Reader, n *int64, err *error) uint { - var size = ReadUint8(r, n, err) - if size > 8 { - setFirstErr(err, errors.New("Uvarint overflow")) - return 0 - } - if size == 0 { - return 0 - } - buf := make([]byte, 8) - ReadFull(buf[(8-size):], r, n, err) - *n += int64(1 + size) - return uint(binary.BigEndian.Uint64(buf)) -} - -func setFirstErr(err *error, newErr error) { - if *err == nil && newErr != nil { - *err = newErr - } -} diff --git a/wire/int_test.go b/wire/int_test.go deleted file mode 100644 index 3baceaa4..00000000 --- a/wire/int_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package wire - -import ( - "bytes" - "fmt" - "testing" -) - -func TestVarint(t *testing.T) { - - check := func(i int, s string) { - buf := new(bytes.Buffer) - n, err := new(int64), new(error) - WriteVarint(i, buf, n, err) - bufBytes := buf.Bytes() // Read before consuming below. - i_ := ReadVarint(buf, n, err) - if i != i_ { - fmt.Println(bufBytes) - t.Fatalf("Encoded %v and got %v", i, i_) - } - if s != "" { - if bufHex := fmt.Sprintf("%X", bufBytes); bufHex != s { - t.Fatalf("Encoded %v, expected %v", bufHex, s) - } - } - } - - // 123457 is some prime. - for i := -(2 << 33); i < (2 << 33); i += 123457 { - check(i, "") - } - - // Near zero - check(-1, "F101") - check(0, "00") - check(1, "0101") - // Positives - check(1<<32-1, "04FFFFFFFF") - check(1<<32+0, "050100000000") - check(1<<32+1, "050100000001") - check(1<<53-1, "071FFFFFFFFFFFFF") - // Negatives - check(-1<<32+1, "F4FFFFFFFF") - check(-1<<32-0, "F50100000000") - check(-1<<32-1, "F50100000001") - check(-1<<53+1, "F71FFFFFFFFFFFFF") -} - -func TestUvarint(t *testing.T) { - - check := func(i uint, s string) { - buf := new(bytes.Buffer) - n, err := new(int64), new(error) - WriteUvarint(i, buf, n, err) - bufBytes := buf.Bytes() - i_ := ReadUvarint(buf, n, err) - if i != i_ { - fmt.Println(buf.Bytes()) - t.Fatalf("Encoded %v and got %v", i, i_) - } - if s != "" { - if bufHex := fmt.Sprintf("%X", bufBytes); bufHex != s { - t.Fatalf("Encoded %v, expected %v", bufHex, s) - } - } - } - - // 123457 is some prime. - for i := 0; i < (2 << 33); i += 123457 { - check(uint(i), "") - } - - check(1, "0101") - check(1<<32-1, "04FFFFFFFF") - check(1<<32+0, "050100000000") - check(1<<32+1, "050100000001") - check(1<<53-1, "071FFFFFFFFFFFFF") - -} diff --git a/wire/log.go b/wire/log.go deleted file mode 100644 index 7b9e509a..00000000 --- a/wire/log.go +++ /dev/null @@ -1,18 +0,0 @@ -package wire - -import ( - "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/log15" - "github.com/tendermint/tendermint/logger" -) - -var log = logger.New("module", "binary") - -func init() { - log.SetHandler( - log15.LvlFilterHandler( - log15.LvlWarn, - //log15.LvlDebug, - logger.RootHandler(), - ), - ) -} diff --git a/wire/reflect.go b/wire/reflect.go deleted file mode 100644 index d964d585..00000000 --- a/wire/reflect.go +++ /dev/null @@ -1,954 +0,0 @@ -package wire - -import ( - "encoding/hex" - "encoding/json" - "errors" - "io" - "reflect" - "sync" - "time" - - . "github.com/tendermint/tendermint/common" -) - -const ( - ReflectSliceChunk = 1024 -) - -type TypeInfo struct { - Type reflect.Type // The type - - // If Type is kind reflect.Interface, is registered - IsRegisteredInterface bool - ByteToType map[byte]reflect.Type - TypeToByte map[reflect.Type]byte - - // If Type is concrete - Byte byte - - // If Type is kind reflect.Struct - Fields []StructFieldInfo -} - -type Options struct { - JSONName string // (JSON) Corresponding JSON field name. (override with `json=""`) - Varint bool // (Binary) Use length-prefixed encoding for (u)int* -} - -func getOptionsFromField(field reflect.StructField) (skip bool, opts Options) { - jsonName := field.Tag.Get("json") - if jsonName == "-" { - skip = true - return - } else if jsonName == "" { - jsonName = field.Name - } - varint := false - binTag := field.Tag.Get("binary") - if binTag == "varint" { // TODO: extend - varint = true - } - opts = Options{ - JSONName: jsonName, - Varint: varint, - } - return -} - -type StructFieldInfo struct { - Index int // Struct field index - Type reflect.Type // Struct field type - Options // Encoding options -} - -func (info StructFieldInfo) unpack() (int, reflect.Type, Options) { - return info.Index, info.Type, info.Options -} - -// e.g. If o is struct{Foo}{}, return is the Foo reflection type. -func GetTypeFromStructDeclaration(o interface{}) reflect.Type { - rt := reflect.TypeOf(o) - if rt.NumField() != 1 { - PanicSanity("Unexpected number of fields in struct-wrapped declaration of type") - } - return rt.Field(0).Type -} - -func SetByteForType(typeByte byte, rt reflect.Type) { - typeInfo := GetTypeInfo(rt) - if typeInfo.Byte != 0x00 && typeInfo.Byte != typeByte { - PanicSanity(Fmt("Type %v already registered with type byte %X", rt, typeByte)) - } - typeInfo.Byte = typeByte - // If pointer, we need to set it for the concrete type as well. - if rt.Kind() == reflect.Ptr { - SetByteForType(typeByte, rt.Elem()) - } -} - -// Predeclaration of common types -var ( - timeType = GetTypeFromStructDeclaration(struct{ time.Time }{}) -) - -const ( - iso8601 = "2006-01-02T15:04:05.000Z" // forced microseconds -) - -// NOTE: do not access typeInfos directly, but call GetTypeInfo() -var typeInfosMtx sync.Mutex -var typeInfos = map[reflect.Type]*TypeInfo{} - -func GetTypeInfo(rt reflect.Type) *TypeInfo { - typeInfosMtx.Lock() - defer typeInfosMtx.Unlock() - info := typeInfos[rt] - if info == nil { - info = MakeTypeInfo(rt) - typeInfos[rt] = info - } - return info -} - -// For use with the RegisterInterface declaration -type ConcreteType struct { - O interface{} - Byte byte -} - -// Must use this to register an interface to properly decode the -// underlying concrete type. -func RegisterInterface(o interface{}, ctypes ...ConcreteType) *TypeInfo { - it := GetTypeFromStructDeclaration(o) - if it.Kind() != reflect.Interface { - PanicSanity("RegisterInterface expects an interface") - } - toType := make(map[byte]reflect.Type, 0) - toByte := make(map[reflect.Type]byte, 0) - for _, ctype := range ctypes { - crt := reflect.TypeOf(ctype.O) - typeByte := ctype.Byte - SetByteForType(typeByte, crt) - if typeByte == 0x00 { - PanicSanity(Fmt("Byte of 0x00 is reserved for nil (%v)", ctype)) - } - if toType[typeByte] != nil { - PanicSanity(Fmt("Duplicate Byte for type %v and %v", ctype, toType[typeByte])) - } - toType[typeByte] = crt - toByte[crt] = typeByte - } - typeInfo := &TypeInfo{ - Type: it, - IsRegisteredInterface: true, - ByteToType: toType, - TypeToByte: toByte, - } - typeInfos[it] = typeInfo - return typeInfo -} - -func MakeTypeInfo(rt reflect.Type) *TypeInfo { - info := &TypeInfo{Type: rt} - - // If struct, register field name options - if rt.Kind() == reflect.Struct { - numFields := rt.NumField() - structFields := []StructFieldInfo{} - for i := 0; i < numFields; i++ { - field := rt.Field(i) - if field.PkgPath != "" { - continue - } - skip, opts := getOptionsFromField(field) - if skip { - continue - } - structFields = append(structFields, StructFieldInfo{ - Index: i, - Type: field.Type, - Options: opts, - }) - } - info.Fields = structFields - } - - return info -} - -// Contract: Caller must ensure that rt is supported -// (e.g. is recursively composed of supported native types, and structs and slices.) -func readReflectBinary(rv reflect.Value, rt reflect.Type, opts Options, r io.Reader, n *int64, err *error) { - - // Get typeInfo - typeInfo := GetTypeInfo(rt) - - if rt.Kind() == reflect.Interface { - if !typeInfo.IsRegisteredInterface { - // There's no way we can read such a thing. - *err = errors.New(Fmt("Cannot read unregistered interface type %v", rt)) - return - } - typeByte := ReadByte(r, n, err) - if *err != nil { - return - } - if typeByte == 0x00 { - return // nil - } - crt, ok := typeInfo.ByteToType[typeByte] - if !ok { - *err = errors.New(Fmt("Unexpected type byte %X for type %v", typeByte, rt)) - return - } - crv := reflect.New(crt).Elem() - r = NewPrefixedReader([]byte{typeByte}, r) - readReflectBinary(crv, crt, opts, r, n, err) - rv.Set(crv) // NOTE: orig rv is ignored. - return - } - - if rt.Kind() == reflect.Ptr { - typeByte := ReadByte(r, n, err) - if *err != nil { - return - } - if typeByte == 0x00 { - return // nil - } - // Create new if rv is nil. - if rv.IsNil() { - newRv := reflect.New(rt.Elem()) - rv.Set(newRv) - rv = newRv - } - // Dereference pointer - rv, rt = rv.Elem(), rt.Elem() - typeInfo = GetTypeInfo(rt) - if typeInfo.Byte != 0x00 { - r = NewPrefixedReader([]byte{typeByte}, r) - } else if typeByte != 0x01 { - *err = errors.New(Fmt("Unexpected type byte %X for ptr of untyped thing", typeByte)) - return - } - // continue... - } - - // Read Byte prefix - if typeInfo.Byte != 0x00 { - typeByte := ReadByte(r, n, err) - if typeByte != typeInfo.Byte { - *err = errors.New(Fmt("Expected Byte of %X but got %X", typeInfo.Byte, typeByte)) - return - } - } - - switch rt.Kind() { - case reflect.Array: - elemRt := rt.Elem() - length := rt.Len() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Bytearrays - buf := make([]byte, length) - ReadFull(buf, r, n, err) - if *err != nil { - return - } - log.Info("Read bytearray", "bytes", buf) - reflect.Copy(rv, reflect.ValueOf(buf)) - } else { - for i := 0; i < length; i++ { - elemRv := rv.Index(i) - readReflectBinary(elemRv, elemRt, opts, r, n, err) - if *err != nil { - return - } - if MaxBinaryReadSize < *n { - *err = ErrBinaryReadSizeOverflow - return - } - } - log.Info(Fmt("Read %v-array", elemRt), "length", length) - } - - case reflect.Slice: - elemRt := rt.Elem() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Byteslices - byteslice := ReadByteSlice(r, n, err) - log.Info("Read byteslice", "bytes", byteslice) - rv.Set(reflect.ValueOf(byteslice)) - } else { - var sliceRv reflect.Value - // Read length - length := ReadVarint(r, n, err) - log.Info(Fmt("Read length: %v", length)) - sliceRv = reflect.MakeSlice(rt, 0, 0) - // read one ReflectSliceChunk at a time and append - for i := 0; i*ReflectSliceChunk < length; i++ { - l := MinInt(ReflectSliceChunk, length-i*ReflectSliceChunk) - tmpSliceRv := reflect.MakeSlice(rt, l, l) - for j := 0; j < l; j++ { - elemRv := tmpSliceRv.Index(j) - readReflectBinary(elemRv, elemRt, opts, r, n, err) - if *err != nil { - return - } - if MaxBinaryReadSize < *n { - *err = ErrBinaryReadSizeOverflow - return - } - } - sliceRv = reflect.AppendSlice(sliceRv, tmpSliceRv) - } - - rv.Set(sliceRv) - } - - case reflect.Struct: - if rt == timeType { - // Special case: time.Time - t := ReadTime(r, n, err) - log.Info(Fmt("Read time: %v", t)) - rv.Set(reflect.ValueOf(t)) - } else { - for _, fieldInfo := range typeInfo.Fields { - i, fieldType, opts := fieldInfo.unpack() - fieldRv := rv.Field(i) - readReflectBinary(fieldRv, fieldType, opts, r, n, err) - } - } - - case reflect.String: - str := ReadString(r, n, err) - log.Info(Fmt("Read string: %v", str)) - rv.SetString(str) - - case reflect.Int64: - if opts.Varint { - num := ReadVarint(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetInt(int64(num)) - } else { - num := ReadInt64(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetInt(int64(num)) - } - - case reflect.Int32: - num := ReadUint32(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetInt(int64(num)) - - case reflect.Int16: - num := ReadUint16(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetInt(int64(num)) - - case reflect.Int8: - num := ReadUint8(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetInt(int64(num)) - - case reflect.Int: - num := ReadVarint(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetInt(int64(num)) - - case reflect.Uint64: - if opts.Varint { - num := ReadVarint(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetUint(uint64(num)) - } else { - num := ReadUint64(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetUint(uint64(num)) - } - - case reflect.Uint32: - num := ReadUint32(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetUint(uint64(num)) - - case reflect.Uint16: - num := ReadUint16(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetUint(uint64(num)) - - case reflect.Uint8: - num := ReadUint8(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetUint(uint64(num)) - - case reflect.Uint: - num := ReadVarint(r, n, err) - log.Info(Fmt("Read num: %v", num)) - rv.SetUint(uint64(num)) - - case reflect.Bool: - num := ReadUint8(r, n, err) - log.Info(Fmt("Read bool: %v", num)) - rv.SetBool(num > 0) - - default: - PanicSanity(Fmt("Unknown field type %v", rt.Kind())) - } -} - -// rv: the reflection value of the thing to write -// rt: the type of rv as declared in the container, not necessarily rv.Type(). -func writeReflectBinary(rv reflect.Value, rt reflect.Type, opts Options, w io.Writer, n *int64, err *error) { - - // Get typeInfo - typeInfo := GetTypeInfo(rt) - - if rt.Kind() == reflect.Interface { - if rv.IsNil() { - // XXX ensure that typeByte 0 is reserved. - WriteByte(0x00, w, n, err) - return - } - crv := rv.Elem() // concrete reflection value - crt := crv.Type() // concrete reflection type - if typeInfo.IsRegisteredInterface { - // See if the crt is registered. - // If so, we're more restrictive. - _, ok := typeInfo.TypeToByte[crt] - if !ok { - switch crt.Kind() { - case reflect.Ptr: - *err = errors.New(Fmt("Unexpected pointer type %v for registered interface %v. "+ - "Was it registered as a value receiver rather than as a pointer receiver?", crt, rt.Name())) - case reflect.Struct: - *err = errors.New(Fmt("Unexpected struct type %v for registered interface %v. "+ - "Was it registered as a pointer receiver rather than as a value receiver?", crt, rt.Name())) - default: - *err = errors.New(Fmt("Unexpected type %v for registered interface %v. "+ - "If this is intentional, please register it.", crt, rt.Name())) - } - return - } - } else { - // We support writing unsafely for convenience. - } - // We don't have to write the typeByte here, - // the writeReflectBinary() call below will write it. - writeReflectBinary(crv, crt, opts, w, n, err) - return - } - - if rt.Kind() == reflect.Ptr { - // Dereference pointer - rv, rt = rv.Elem(), rt.Elem() - typeInfo = GetTypeInfo(rt) - if !rv.IsValid() { - // For better compatibility with other languages, - // as far as tendermint/wire is concerned, - // pointers to nil values are the same as nil. - WriteByte(0x00, w, n, err) - return - } - if typeInfo.Byte == 0x00 { - WriteByte(0x01, w, n, err) - // continue... - } else { - // continue... - } - } - - // Write type byte - if typeInfo.Byte != 0x00 { - WriteByte(typeInfo.Byte, w, n, err) - } - - // All other types - switch rt.Kind() { - case reflect.Array: - elemRt := rt.Elem() - length := rt.Len() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Bytearrays - if rv.CanAddr() { - byteslice := rv.Slice(0, length).Bytes() - WriteTo(byteslice, w, n, err) - } else { - buf := make([]byte, length) - reflect.Copy(reflect.ValueOf(buf), rv) - WriteTo(buf, w, n, err) - } - } else { - // Write elems - for i := 0; i < length; i++ { - elemRv := rv.Index(i) - writeReflectBinary(elemRv, elemRt, opts, w, n, err) - } - } - - case reflect.Slice: - elemRt := rt.Elem() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Byteslices - byteslice := rv.Bytes() - WriteByteSlice(byteslice, w, n, err) - } else { - // Write length - length := rv.Len() - WriteVarint(length, w, n, err) - // Write elems - for i := 0; i < length; i++ { - elemRv := rv.Index(i) - writeReflectBinary(elemRv, elemRt, opts, w, n, err) - } - } - - case reflect.Struct: - if rt == timeType { - // Special case: time.Time - WriteTime(rv.Interface().(time.Time), w, n, err) - } else { - for _, fieldInfo := range typeInfo.Fields { - i, fieldType, opts := fieldInfo.unpack() - fieldRv := rv.Field(i) - writeReflectBinary(fieldRv, fieldType, opts, w, n, err) - } - } - - case reflect.String: - WriteString(rv.String(), w, n, err) - - case reflect.Int64: - if opts.Varint { - WriteVarint(int(rv.Int()), w, n, err) - } else { - WriteInt64(rv.Int(), w, n, err) - } - - case reflect.Int32: - WriteInt32(int32(rv.Int()), w, n, err) - - case reflect.Int16: - WriteInt16(int16(rv.Int()), w, n, err) - - case reflect.Int8: - WriteInt8(int8(rv.Int()), w, n, err) - - case reflect.Int: - WriteVarint(int(rv.Int()), w, n, err) - - case reflect.Uint64: - if opts.Varint { - WriteUvarint(uint(rv.Uint()), w, n, err) - } else { - WriteUint64(rv.Uint(), w, n, err) - } - - case reflect.Uint32: - WriteUint32(uint32(rv.Uint()), w, n, err) - - case reflect.Uint16: - WriteUint16(uint16(rv.Uint()), w, n, err) - - case reflect.Uint8: - WriteUint8(uint8(rv.Uint()), w, n, err) - - case reflect.Uint: - WriteUvarint(uint(rv.Uint()), w, n, err) - - case reflect.Bool: - if rv.Bool() { - WriteUint8(uint8(1), w, n, err) - } else { - WriteUint8(uint8(0), w, n, err) - } - - default: - PanicSanity(Fmt("Unknown field type %v", rt.Kind())) - } -} - -//----------------------------------------------------------------------------- - -func readByteJSON(o interface{}) (typeByte byte, rest interface{}, err error) { - oSlice, ok := o.([]interface{}) - if !ok { - err = errors.New(Fmt("Expected type [Byte,?] but got type %v", reflect.TypeOf(o))) - return - } - if len(oSlice) != 2 { - err = errors.New(Fmt("Expected [Byte,?] len 2 but got len %v", len(oSlice))) - return - } - typeByte_, ok := oSlice[0].(float64) - typeByte = byte(typeByte_) - rest = oSlice[1] - return -} - -// Contract: Caller must ensure that rt is supported -// (e.g. is recursively composed of supported native types, and structs and slices.) -// rv and rt refer to the object we're unmarhsaling into, whereas o is the result of naiive json unmarshal (map[string]interface{}) -func readReflectJSON(rv reflect.Value, rt reflect.Type, o interface{}, err *error) { - - // Get typeInfo - typeInfo := GetTypeInfo(rt) - - if rt.Kind() == reflect.Interface { - if !typeInfo.IsRegisteredInterface { - // There's no way we can read such a thing. - *err = errors.New(Fmt("Cannot read unregistered interface type %v", rt)) - return - } - if o == nil { - return // nil - } - typeByte, _, err_ := readByteJSON(o) - if err_ != nil { - *err = err_ - return - } - crt, ok := typeInfo.ByteToType[typeByte] - if !ok { - *err = errors.New(Fmt("Byte %X not registered for interface %v", typeByte, rt)) - return - } - crv := reflect.New(crt).Elem() - readReflectJSON(crv, crt, o, err) - rv.Set(crv) // NOTE: orig rv is ignored. - return - } - - if rt.Kind() == reflect.Ptr { - if o == nil { - return // nil - } - // Create new struct if rv is nil. - if rv.IsNil() { - newRv := reflect.New(rt.Elem()) - rv.Set(newRv) - rv = newRv - } - // Dereference pointer - rv, rt = rv.Elem(), rt.Elem() - typeInfo = GetTypeInfo(rt) - // continue... - } - - // Read Byte prefix - if typeInfo.Byte != 0x00 { - typeByte, rest, err_ := readByteJSON(o) - if err_ != nil { - *err = err_ - return - } - if typeByte != typeInfo.Byte { - *err = errors.New(Fmt("Expected Byte of %X but got %X", typeInfo.Byte, byte(typeByte))) - return - } - o = rest - } - - switch rt.Kind() { - case reflect.Array: - elemRt := rt.Elem() - length := rt.Len() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Bytearrays - oString, ok := o.(string) - if !ok { - *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - buf, err_ := hex.DecodeString(oString) - if err_ != nil { - *err = err_ - return - } - if len(buf) != length { - *err = errors.New(Fmt("Expected bytearray of length %v but got %v", length, len(buf))) - return - } - log.Info("Read bytearray", "bytes", buf) - reflect.Copy(rv, reflect.ValueOf(buf)) - } else { - oSlice, ok := o.([]interface{}) - if !ok { - *err = errors.New(Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o))) - return - } - if len(oSlice) != length { - *err = errors.New(Fmt("Expected array of length %v but got %v", length, len(oSlice))) - return - } - for i := 0; i < length; i++ { - elemRv := rv.Index(i) - readReflectJSON(elemRv, elemRt, oSlice[i], err) - } - log.Info(Fmt("Read %v-array", elemRt), "length", length) - } - - case reflect.Slice: - elemRt := rt.Elem() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Byteslices - oString, ok := o.(string) - if !ok { - *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - byteslice, err_ := hex.DecodeString(oString) - if err_ != nil { - *err = err_ - return - } - log.Info("Read byteslice", "bytes", byteslice) - rv.Set(reflect.ValueOf(byteslice)) - } else { - // Read length - oSlice, ok := o.([]interface{}) - if !ok { - *err = errors.New(Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o))) - return - } - length := len(oSlice) - log.Info(Fmt("Read length: %v", length)) - sliceRv := reflect.MakeSlice(rt, length, length) - // Read elems - for i := 0; i < length; i++ { - elemRv := sliceRv.Index(i) - readReflectJSON(elemRv, elemRt, oSlice[i], err) - } - rv.Set(sliceRv) - } - - case reflect.Struct: - if rt == timeType { - // Special case: time.Time - str, ok := o.(string) - if !ok { - *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - log.Info(Fmt("Read time: %v", str)) - t, err_ := time.Parse(iso8601, str) - if err_ != nil { - *err = err_ - return - } - rv.Set(reflect.ValueOf(t)) - } else { - oMap, ok := o.(map[string]interface{}) - if !ok { - *err = errors.New(Fmt("Expected map but got type %v", reflect.TypeOf(o))) - return - } - // TODO: ensure that all fields are set? - // TODO: disallow unknown oMap fields? - for _, fieldInfo := range typeInfo.Fields { - i, fieldType, opts := fieldInfo.unpack() - value, ok := oMap[opts.JSONName] - if !ok { - continue // Skip missing fields. - } - fieldRv := rv.Field(i) - readReflectJSON(fieldRv, fieldType, value, err) - } - } - - case reflect.String: - str, ok := o.(string) - if !ok { - *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - log.Info(Fmt("Read string: %v", str)) - rv.SetString(str) - - case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: - num, ok := o.(float64) - if !ok { - *err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) - return - } - log.Info(Fmt("Read num: %v", num)) - rv.SetInt(int64(num)) - - case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: - num, ok := o.(float64) - if !ok { - *err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) - return - } - if num < 0 { - *err = errors.New(Fmt("Expected unsigned numeric but got %v", num)) - return - } - log.Info(Fmt("Read num: %v", num)) - rv.SetUint(uint64(num)) - - case reflect.Bool: - bl, ok := o.(bool) - if !ok { - *err = errors.New(Fmt("Expected boolean but got type %v", reflect.TypeOf(o))) - return - } - log.Info(Fmt("Read boolean: %v", bl)) - rv.SetBool(bl) - - default: - PanicSanity(Fmt("Unknown field type %v", rt.Kind())) - } -} - -func writeReflectJSON(rv reflect.Value, rt reflect.Type, w io.Writer, n *int64, err *error) { - log.Info(Fmt("writeReflectJSON(%v, %v, %v, %v, %v)", rv, rt, w, n, err)) - - // Get typeInfo - typeInfo := GetTypeInfo(rt) - - if rt.Kind() == reflect.Interface { - if rv.IsNil() { - // XXX ensure that typeByte 0 is reserved. - WriteTo([]byte("null"), w, n, err) - return - } - crv := rv.Elem() // concrete reflection value - crt := crv.Type() // concrete reflection type - if typeInfo.IsRegisteredInterface { - // See if the crt is registered. - // If so, we're more restrictive. - _, ok := typeInfo.TypeToByte[crt] - if !ok { - switch crt.Kind() { - case reflect.Ptr: - *err = errors.New(Fmt("Unexpected pointer type %v for registered interface %v. "+ - "Was it registered as a value receiver rather than as a pointer receiver?", crt, rt.Name())) - case reflect.Struct: - *err = errors.New(Fmt("Unexpected struct type %v for registered interface %v. "+ - "Was it registered as a pointer receiver rather than as a value receiver?", crt, rt.Name())) - default: - *err = errors.New(Fmt("Unexpected type %v for registered interface %v. "+ - "If this is intentional, please register it.", crt, rt.Name())) - } - return - } - } else { - // We support writing unsafely for convenience. - } - // We don't have to write the typeByte here, - // the writeReflectJSON() call below will write it. - writeReflectJSON(crv, crt, w, n, err) - return - } - - if rt.Kind() == reflect.Ptr { - // Dereference pointer - rv, rt = rv.Elem(), rt.Elem() - typeInfo = GetTypeInfo(rt) - if !rv.IsValid() { - // For better compatibility with other languages, - // as far as tendermint/wire is concerned, - // pointers to nil values are the same as nil. - WriteTo([]byte("null"), w, n, err) - return - } - // continue... - } - - // Write Byte - if typeInfo.Byte != 0x00 { - WriteTo([]byte(Fmt("[%v,", typeInfo.Byte)), w, n, err) - defer WriteTo([]byte("]"), w, n, err) - } - - // All other types - switch rt.Kind() { - case reflect.Array: - elemRt := rt.Elem() - length := rt.Len() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Bytearray - bytearray := reflect.ValueOf(make([]byte, length)) - reflect.Copy(bytearray, rv) - WriteTo([]byte(Fmt("\"%X\"", bytearray.Interface())), w, n, err) - } else { - WriteTo([]byte("["), w, n, err) - // Write elems - for i := 0; i < length; i++ { - elemRv := rv.Index(i) - writeReflectJSON(elemRv, elemRt, w, n, err) - if i < length-1 { - WriteTo([]byte(","), w, n, err) - } - } - WriteTo([]byte("]"), w, n, err) - } - - case reflect.Slice: - elemRt := rt.Elem() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Byteslices - byteslice := rv.Bytes() - WriteTo([]byte(Fmt("\"%X\"", byteslice)), w, n, err) - } else { - WriteTo([]byte("["), w, n, err) - // Write elems - length := rv.Len() - for i := 0; i < length; i++ { - elemRv := rv.Index(i) - writeReflectJSON(elemRv, elemRt, w, n, err) - if i < length-1 { - WriteTo([]byte(","), w, n, err) - } - } - WriteTo([]byte("]"), w, n, err) - } - - case reflect.Struct: - if rt == timeType { - // Special case: time.Time - t := rv.Interface().(time.Time).UTC() - str := t.Format(iso8601) - jsonBytes, err_ := json.Marshal(str) - if err_ != nil { - *err = err_ - return - } - WriteTo(jsonBytes, w, n, err) - } else { - WriteTo([]byte("{"), w, n, err) - wroteField := false - for _, fieldInfo := range typeInfo.Fields { - i, fieldType, opts := fieldInfo.unpack() - fieldRv := rv.Field(i) - if wroteField { - WriteTo([]byte(","), w, n, err) - } else { - wroteField = true - } - WriteTo([]byte(Fmt("\"%v\":", opts.JSONName)), w, n, err) - writeReflectJSON(fieldRv, fieldType, w, n, err) - } - WriteTo([]byte("}"), w, n, err) - } - - case reflect.String: - fallthrough - case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: - fallthrough - case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: - fallthrough - case reflect.Bool: - jsonBytes, err_ := json.Marshal(rv.Interface()) - if err_ != nil { - *err = err_ - return - } - WriteTo(jsonBytes, w, n, err) - - default: - PanicSanity(Fmt("Unknown field type %v", rt.Kind())) - } - -} diff --git a/wire/reflect_test.go b/wire/reflect_test.go deleted file mode 100644 index b21b8bf2..00000000 --- a/wire/reflect_test.go +++ /dev/null @@ -1,508 +0,0 @@ -package wire - -import ( - "bytes" - "fmt" - "reflect" - "testing" - "time" - - . "github.com/tendermint/tendermint/common" -) - -type SimpleStruct struct { - String string - Bytes []byte - Time time.Time -} - -type Animal interface{} - -const ( - AnimalTypeCat = byte(0x01) - AnimalTypeDog = byte(0x02) - AnimalTypeSnake = byte(0x03) - AnimalTypeViper = byte(0x04) -) - -// Implements Animal -type Cat struct { - SimpleStruct -} - -// Implements Animal -type Dog struct { - SimpleStruct -} - -// Implements Animal -type Snake []byte - -// Implements Animal -type Viper struct { - Bytes []byte -} - -var _ = RegisterInterface( - struct{ Animal }{}, - ConcreteType{Cat{}, AnimalTypeCat}, - ConcreteType{Dog{}, AnimalTypeDog}, - ConcreteType{Snake{}, AnimalTypeSnake}, - ConcreteType{&Viper{}, AnimalTypeViper}, -) - -// TODO: add assertions here ... -func TestAnimalInterface(t *testing.T) { - var foo Animal - - // Type of pointer to Animal - rt := reflect.TypeOf(&foo) - fmt.Printf("rt: %v\n", rt) - - // Type of Animal itself. - // NOTE: normally this is acquired through other means - // like introspecting on method signatures, or struct fields. - rte := rt.Elem() - fmt.Printf("rte: %v\n", rte) - - // Get a new pointer to the interface - // NOTE: calling .Interface() is to get the actual value, - // instead of reflection values. - ptr := reflect.New(rte).Interface() - fmt.Printf("ptr: %v", ptr) - - // Make a binary byteslice that represents a *snake. - foo = Snake([]byte("snake")) - snakeBytes := BinaryBytes(foo) - snakeReader := bytes.NewReader(snakeBytes) - - // Now you can read it. - n, err := new(int64), new(error) - it := ReadBinary(foo, snakeReader, n, err).(Animal) - fmt.Println(it, reflect.TypeOf(it)) -} - -//------------------------------------- - -type Constructor func() interface{} -type Instantiator func() (o interface{}, ptr interface{}) -type Validator func(o interface{}, t *testing.T) - -type TestCase struct { - Constructor - Instantiator - Validator -} - -//------------------------------------- - -func constructBasic() interface{} { - cat := Cat{ - SimpleStruct{ - String: "String", - Bytes: []byte("Bytes"), - Time: time.Unix(123, 456789999), - }, - } - return cat -} - -func instantiateBasic() (interface{}, interface{}) { - return Cat{}, &Cat{} -} - -func validateBasic(o interface{}, t *testing.T) { - cat := o.(Cat) - if cat.String != "String" { - t.Errorf("Expected cat.String == 'String', got %v", cat.String) - } - if string(cat.Bytes) != "Bytes" { - t.Errorf("Expected cat.Bytes == 'Bytes', got %X", cat.Bytes) - } - if cat.Time.UnixNano() != 123456000000 { // Only milliseconds - t.Errorf("Expected cat.Time.UnixNano() == 123456000000, got %v", cat.Time.UnixNano()) - } -} - -//------------------------------------- - -type NilTestStruct struct { - IntPtr *int - CatPtr *Cat - Animal Animal -} - -func constructNilTestStruct() interface{} { - return NilTestStruct{} -} - -func instantiateNilTestStruct() (interface{}, interface{}) { - return NilTestStruct{}, &NilTestStruct{} -} - -func validateNilTestStruct(o interface{}, t *testing.T) { - nts := o.(NilTestStruct) - if nts.IntPtr != nil { - t.Errorf("Expected nts.IntPtr to be nil, got %v", nts.IntPtr) - } - if nts.CatPtr != nil { - t.Errorf("Expected nts.CatPtr to be nil, got %v", nts.CatPtr) - } - if nts.Animal != nil { - t.Errorf("Expected nts.Animal to be nil, got %v", nts.Animal) - } -} - -//------------------------------------- - -type ComplexStruct struct { - Name string - Animal Animal -} - -func constructComplex() interface{} { - c := ComplexStruct{ - Name: "Complex", - Animal: constructBasic(), - } - return c -} - -func instantiateComplex() (interface{}, interface{}) { - return ComplexStruct{}, &ComplexStruct{} -} - -func validateComplex(o interface{}, t *testing.T) { - c2 := o.(ComplexStruct) - if cat, ok := c2.Animal.(Cat); ok { - validateBasic(cat, t) - } else { - t.Errorf("Expected c2.Animal to be of type cat, got %v", reflect.ValueOf(c2.Animal).Elem().Type()) - } -} - -//------------------------------------- - -type ComplexStruct2 struct { - Cat Cat - Dog *Dog - Snake Snake - Snake2 *Snake - Viper Viper - Viper2 *Viper -} - -func constructComplex2() interface{} { - snake_ := Snake([]byte("hiss")) - snakePtr_ := &snake_ - - c := ComplexStruct2{ - Cat: Cat{ - SimpleStruct{ - String: "String", - Bytes: []byte("Bytes"), - }, - }, - Dog: &Dog{ - SimpleStruct{ - String: "Woof", - Bytes: []byte("Bark"), - }, - }, - Snake: Snake([]byte("hiss")), - Snake2: snakePtr_, - Viper: Viper{Bytes: []byte("hizz")}, - Viper2: &Viper{Bytes: []byte("hizz")}, - } - return c -} - -func instantiateComplex2() (interface{}, interface{}) { - return ComplexStruct2{}, &ComplexStruct2{} -} - -func validateComplex2(o interface{}, t *testing.T) { - c2 := o.(ComplexStruct2) - cat := c2.Cat - if cat.String != "String" { - t.Errorf("Expected cat.String == 'String', got %v", cat.String) - } - if string(cat.Bytes) != "Bytes" { - t.Errorf("Expected cat.Bytes == 'Bytes', got %X", cat.Bytes) - } - - dog := c2.Dog - if dog.String != "Woof" { - t.Errorf("Expected dog.String == 'Woof', got %v", dog.String) - } - if string(dog.Bytes) != "Bark" { - t.Errorf("Expected dog.Bytes == 'Bark', got %X", dog.Bytes) - } - - snake := c2.Snake - if string(snake) != "hiss" { - t.Errorf("Expected string(snake) == 'hiss', got %v", string(snake)) - } - - snake2 := c2.Snake2 - if string(*snake2) != "hiss" { - t.Errorf("Expected string(snake2) == 'hiss', got %v", string(*snake2)) - } - - viper := c2.Viper - if string(viper.Bytes) != "hizz" { - t.Errorf("Expected string(viper.Bytes) == 'hizz', got %v", string(viper.Bytes)) - } - - viper2 := c2.Viper2 - if string(viper2.Bytes) != "hizz" { - t.Errorf("Expected string(viper2.Bytes) == 'hizz', got %v", string(viper2.Bytes)) - } -} - -//------------------------------------- - -type ComplexStructArray struct { - Animals []Animal - Bytes [5]byte - Ints [5]int - Array SimpleArray -} - -func constructComplexArray() interface{} { - c := ComplexStructArray{ - Animals: []Animal{ - Cat{ - SimpleStruct{ - String: "String", - Bytes: []byte("Bytes"), - }, - }, - Dog{ - SimpleStruct{ - String: "Woof", - Bytes: []byte("Bark"), - }, - }, - Snake([]byte("hiss")), - &Viper{ - Bytes: []byte("hizz"), - }, - }, - Bytes: [5]byte{1, 10, 50, 100, 200}, - Ints: [5]int{1, 2, 3, 4, 5}, - Array: SimpleArray([5]byte{1, 10, 50, 100, 200}), - } - return c -} - -func instantiateComplexArray() (interface{}, interface{}) { - return ComplexStructArray{}, &ComplexStructArray{} -} - -func validateComplexArray(o interface{}, t *testing.T) { - c2 := o.(ComplexStructArray) - if cat, ok := c2.Animals[0].(Cat); ok { - if cat.String != "String" { - t.Errorf("Expected cat.String == 'String', got %v", cat.String) - } - if string(cat.Bytes) != "Bytes" { - t.Errorf("Expected cat.Bytes == 'Bytes', got %X", cat.Bytes) - } - } else { - t.Errorf("Expected c2.Animals[0] to be of type cat, got %v", reflect.ValueOf(c2.Animals[0]).Elem().Type()) - } - - if dog, ok := c2.Animals[1].(Dog); ok { - if dog.String != "Woof" { - t.Errorf("Expected dog.String == 'Woof', got %v", dog.String) - } - if string(dog.Bytes) != "Bark" { - t.Errorf("Expected dog.Bytes == 'Bark', got %X", dog.Bytes) - } - } else { - t.Errorf("Expected c2.Animals[1] to be of type dog, got %v", reflect.ValueOf(c2.Animals[1]).Elem().Type()) - } - - if snake, ok := c2.Animals[2].(Snake); ok { - if string(snake) != "hiss" { - t.Errorf("Expected string(snake) == 'hiss', got %v", string(snake)) - } - } else { - t.Errorf("Expected c2.Animals[2] to be of type Snake, got %v", reflect.ValueOf(c2.Animals[2]).Elem().Type()) - } - - if viper, ok := c2.Animals[3].(*Viper); ok { - if string(viper.Bytes) != "hizz" { - t.Errorf("Expected string(viper.Bytes) == 'hizz', got %v", string(viper.Bytes)) - } - } else { - t.Errorf("Expected c2.Animals[3] to be of type *Viper, got %v", reflect.ValueOf(c2.Animals[3]).Elem().Type()) - } -} - -//----------------------------------------------------------------------------- - -var testCases = []TestCase{} - -func init() { - testCases = append(testCases, TestCase{constructBasic, instantiateBasic, validateBasic}) - testCases = append(testCases, TestCase{constructComplex, instantiateComplex, validateComplex}) - testCases = append(testCases, TestCase{constructComplex2, instantiateComplex2, validateComplex2}) - testCases = append(testCases, TestCase{constructComplexArray, instantiateComplexArray, validateComplexArray}) - testCases = append(testCases, TestCase{constructNilTestStruct, instantiateNilTestStruct, validateNilTestStruct}) -} - -func TestBinary(t *testing.T) { - - for i, testCase := range testCases { - - log.Notice(fmt.Sprintf("Running test case %v", i)) - - // Construct an object - o := testCase.Constructor() - - // Write the object - data := BinaryBytes(o) - t.Logf("Binary: %X", data) - - instance, instancePtr := testCase.Instantiator() - - // Read onto a struct - n, err := new(int64), new(error) - res := ReadBinary(instance, bytes.NewReader(data), n, err) - if *err != nil { - t.Fatalf("Failed to read into instance: %v", *err) - } - - // Validate object - testCase.Validator(res, t) - - // Read onto a pointer - n, err = new(int64), new(error) - res = ReadBinaryPtr(instancePtr, bytes.NewReader(data), n, err) - if *err != nil { - t.Fatalf("Failed to read into instance: %v", *err) - } - - if res != instancePtr { - t.Errorf("Expected pointer to pass through") - } - - // Validate object - testCase.Validator(reflect.ValueOf(res).Elem().Interface(), t) - } - -} - -func TestJSON(t *testing.T) { - - for i, testCase := range testCases { - - log.Notice(fmt.Sprintf("Running test case %v", i)) - - // Construct an object - o := testCase.Constructor() - - // Write the object - data := JSONBytes(o) - t.Logf("JSON: %v", string(data)) - - instance, instancePtr := testCase.Instantiator() - - // Read onto a struct - err := new(error) - res := ReadJSON(instance, data, err) - if *err != nil { - t.Fatalf("Failed to read cat: %v", *err) - } - - // Validate object - testCase.Validator(res, t) - - // Read onto a pointer - res = ReadJSON(instancePtr, data, err) - if *err != nil { - t.Fatalf("Failed to read cat: %v", *err) - } - - if res != instancePtr { - t.Errorf("Expected pointer to pass through") - } - - // Validate object - testCase.Validator(reflect.ValueOf(res).Elem().Interface(), t) - } - -} - -//------------------------------------------------------------------------------ - -type Foo struct { - FieldA string `json:"fieldA"` // json field name is "fieldA" - FieldB string // json field name is "FieldB" - fieldC string // not exported, not serialized. -} - -func TestJSONFieldNames(t *testing.T) { - for i := 0; i < 20; i++ { // Try to ensure deterministic success. - foo := Foo{"a", "b", "c"} - stringified := string(JSONBytes(foo)) - expected := `{"fieldA":"a","FieldB":"b"}` - if stringified != expected { - t.Fatalf("JSONFieldNames error: expected %v, got %v", - expected, stringified) - } - } -} - -//------------------------------------------------------------------------------ - -func TestBadAlloc(t *testing.T) { - n, err := new(int64), new(error) - instance := new([]byte) - data := RandBytes(100 * 1024) - b := new(bytes.Buffer) - // this slice of data claims to be much bigger than it really is - WriteUvarint(uint(10000000000000000), b, n, err) - b.Write(data) - res := ReadBinary(instance, b, n, err) - fmt.Println(res, *err) -} - -//------------------------------------------------------------------------------ - -type SimpleArray [5]byte - -func TestSimpleArray(t *testing.T) { - var foo SimpleArray - - // Type of pointer to array - rt := reflect.TypeOf(&foo) - fmt.Printf("rt: %v\n", rt) // *binary.SimpleArray - - // Type of array itself. - // NOTE: normally this is acquired through other means - // like introspecting on method signatures, or struct fields. - rte := rt.Elem() - fmt.Printf("rte: %v\n", rte) // binary.SimpleArray - - // Get a new pointer to the array - // NOTE: calling .Interface() is to get the actual value, - // instead of reflection values. - ptr := reflect.New(rte).Interface() - fmt.Printf("ptr: %v\n", ptr) // &[0 0 0 0 0] - - // Make a simple int aray - fooArray := SimpleArray([5]byte{1, 10, 50, 100, 200}) - fooBytes := BinaryBytes(fooArray) - fooReader := bytes.NewReader(fooBytes) - - // Now you can read it. - n, err := new(int64), new(error) - it := ReadBinary(foo, fooReader, n, err).(SimpleArray) - - if !bytes.Equal(it[:], fooArray[:]) { - t.Errorf("Expected %v but got %v", fooArray, it) - } -} diff --git a/wire/string.go b/wire/string.go deleted file mode 100644 index 00ee3e99..00000000 --- a/wire/string.go +++ /dev/null @@ -1,33 +0,0 @@ -package wire - -import ( - "io" - - . "github.com/tendermint/tendermint/common" -) - -// String - -func WriteString(s string, w io.Writer, n *int64, err *error) { - WriteVarint(len(s), w, n, err) - WriteTo([]byte(s), w, n, err) -} - -func ReadString(r io.Reader, n *int64, err *error) string { - length := ReadVarint(r, n, err) - if *err != nil { - return "" - } - if length < 0 { - *err = ErrBinaryReadSizeUnderflow - return "" - } - if MaxBinaryReadSize < MaxInt64(int64(length), *n+int64(length)) { - *err = ErrBinaryReadSizeOverflow - return "" - } - - buf := make([]byte, length) - ReadFull(buf, r, n, err) - return string(buf) -} diff --git a/wire/time.go b/wire/time.go deleted file mode 100644 index fde8b8ae..00000000 --- a/wire/time.go +++ /dev/null @@ -1,27 +0,0 @@ -package wire - -import ( - "io" - "time" - - . "github.com/tendermint/tendermint/common" -) - -/* -Writes nanoseconds since epoch but with millisecond precision. -This is to ease compatibility with Javascript etc. -*/ - -func WriteTime(t time.Time, w io.Writer, n *int64, err *error) { - nanosecs := t.UnixNano() - millisecs := nanosecs / 1000000 - WriteInt64(millisecs*1000000, w, n, err) -} - -func ReadTime(r io.Reader, n *int64, err *error) time.Time { - t := ReadInt64(r, n, err) - if t%1000000 != 0 { - PanicSanity("Time cannot have sub-millisecond precision") - } - return time.Unix(0, t) -} diff --git a/wire/util.go b/wire/util.go deleted file mode 100644 index 0b70194d..00000000 --- a/wire/util.go +++ /dev/null @@ -1,78 +0,0 @@ -package wire - -import ( - "bytes" - "crypto/sha256" - "encoding/json" - - "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" - - . "github.com/tendermint/tendermint/common" -) - -func BinaryBytes(o interface{}) []byte { - w, n, err := new(bytes.Buffer), new(int64), new(error) - WriteBinary(o, w, n, err) - if *err != nil { - PanicSanity(*err) - } - return w.Bytes() -} - -func JSONBytes(o interface{}) []byte { - w, n, err := new(bytes.Buffer), new(int64), new(error) - WriteJSON(o, w, n, err) - if *err != nil { - PanicSanity(*err) - } - return w.Bytes() -} - -// NOTE: inefficient -func JSONBytesPretty(o interface{}) []byte { - jsonBytes := JSONBytes(o) - var object interface{} - err := json.Unmarshal(jsonBytes, &object) - if err != nil { - PanicSanity(err) - } - jsonBytes, err = json.MarshalIndent(object, "", "\t") - if err != nil { - PanicSanity(err) - } - return jsonBytes -} - -// NOTE: does not care about the type, only the binary representation. -func BinaryEqual(a, b interface{}) bool { - aBytes := BinaryBytes(a) - bBytes := BinaryBytes(b) - return bytes.Equal(aBytes, bBytes) -} - -// NOTE: does not care about the type, only the binary representation. -func BinaryCompare(a, b interface{}) int { - aBytes := BinaryBytes(a) - bBytes := BinaryBytes(b) - return bytes.Compare(aBytes, bBytes) -} - -// NOTE: only use this if you need 32 bytes. -func BinarySha256(o interface{}) []byte { - hasher, n, err := sha256.New(), new(int64), new(error) - WriteBinary(o, hasher, n, err) - if *err != nil { - PanicSanity(*err) - } - return hasher.Sum(nil) -} - -// NOTE: The default hash function is Ripemd160. -func BinaryRipemd160(o interface{}) []byte { - hasher, n, err := ripemd160.New(), new(int64), new(error) - WriteBinary(o, hasher, n, err) - if *err != nil { - PanicSanity(*err) - } - return hasher.Sum(nil) -} diff --git a/wire/version.go b/wire/version.go deleted file mode 100644 index 58953255..00000000 --- a/wire/version.go +++ /dev/null @@ -1,3 +0,0 @@ -package wire - -const Version = "0.5.0" diff --git a/wire/wire.go b/wire/wire.go deleted file mode 100644 index aece054f..00000000 --- a/wire/wire.go +++ /dev/null @@ -1,134 +0,0 @@ -package wire - -import ( - "encoding/json" - "errors" - "io" - "reflect" - - . "github.com/tendermint/tendermint/common" -) - -// TODO document and maybe make it configurable. -const MaxBinaryReadSize = 21 * 1024 * 1024 - -var ErrBinaryReadSizeOverflow = errors.New("Error: binary read size overflow") -var ErrBinaryReadSizeUnderflow = errors.New("Error: binary read size underflow") - -func ReadBinary(o interface{}, r io.Reader, n *int64, err *error) interface{} { - rv, rt := reflect.ValueOf(o), reflect.TypeOf(o) - if rv.Kind() == reflect.Ptr { - if rv.IsNil() { - // This allows ReadBinaryObject() to return a nil pointer, - // if the value read is nil. - rvPtr := reflect.New(rt) - ReadBinaryPtr(rvPtr.Interface(), r, n, err) - return rvPtr.Elem().Interface() - } else { - readReflectBinary(rv, rt, Options{}, r, n, err) - return o - } - } else { - ptrRv := reflect.New(rt) - readReflectBinary(ptrRv.Elem(), rt, Options{}, r, n, err) - return ptrRv.Elem().Interface() - } -} - -func ReadBinaryPtr(o interface{}, r io.Reader, n *int64, err *error) interface{} { - rv, rt := reflect.ValueOf(o), reflect.TypeOf(o) - if rv.Kind() == reflect.Ptr { - readReflectBinary(rv.Elem(), rt.Elem(), Options{}, r, n, err) - } else { - PanicSanity("ReadBinaryPtr expects o to be a pointer") - } - return o -} - -func WriteBinary(o interface{}, w io.Writer, n *int64, err *error) { - rv := reflect.ValueOf(o) - rt := reflect.TypeOf(o) - writeReflectBinary(rv, rt, Options{}, w, n, err) -} - -func ReadJSON(o interface{}, bytes []byte, err *error) interface{} { - var object interface{} - *err = json.Unmarshal(bytes, &object) - if *err != nil { - return o - } - - return ReadJSONObject(o, object, err) -} - -func ReadJSONPtr(o interface{}, bytes []byte, err *error) interface{} { - var object interface{} - *err = json.Unmarshal(bytes, &object) - if *err != nil { - return o - } - - return ReadJSONObjectPtr(o, object, err) -} - -// o is the ultimate destination, object is the result of json unmarshal -func ReadJSONObject(o interface{}, object interface{}, err *error) interface{} { - rv, rt := reflect.ValueOf(o), reflect.TypeOf(o) - if rv.Kind() == reflect.Ptr { - if rv.IsNil() { - // This allows ReadJSONObject() to return a nil pointer - // if the value read is nil. - rvPtr := reflect.New(rt) - ReadJSONObjectPtr(rvPtr.Interface(), object, err) - return rvPtr.Elem().Interface() - } else { - readReflectJSON(rv, rt, object, err) - return o - } - } else { - ptrRv := reflect.New(rt) - readReflectJSON(ptrRv.Elem(), rt, object, err) - return ptrRv.Elem().Interface() - } -} - -func ReadJSONObjectPtr(o interface{}, object interface{}, err *error) interface{} { - rv, rt := reflect.ValueOf(o), reflect.TypeOf(o) - if rv.Kind() == reflect.Ptr { - readReflectJSON(rv.Elem(), rt.Elem(), object, err) - } else { - PanicSanity("ReadJSON(Object)Ptr expects o to be a pointer") - } - return o -} - -func WriteJSON(o interface{}, w io.Writer, n *int64, err *error) { - rv := reflect.ValueOf(o) - rt := reflect.TypeOf(o) - if rv.Kind() == reflect.Ptr { - rv, rt = rv.Elem(), rt.Elem() - } - writeReflectJSON(rv, rt, w, n, err) -} - -// Write all of bz to w -// Increment n and set err accordingly. -func WriteTo(bz []byte, w io.Writer, n *int64, err *error) { - if *err != nil { - return - } - n_, err_ := w.Write(bz) - *n += int64(n_) - *err = err_ -} - -// Read len(buf) from r -// Increment n and set err accordingly. -func ReadFull(buf []byte, r io.Reader, n *int64, err *error) { - if *err != nil { - return - } - n_, err_ := io.ReadFull(r, buf) - *n += int64(n_) - *err = err_ -}