From 5c5935519a1356facd5527b35022125893789b08 Mon Sep 17 00:00:00 2001 From: Captain Date: Sun, 27 Dec 2020 13:44:23 +0000 Subject: [PATCH] DERO Homomorphic Encryption Testnet Release4 --- astrobwt/astrobwt.go | 5 +- astrobwt/astrobwt_optimized.go | 2 +- blockchain/blockchain.go | 247 +- blockchain/blockheader.go | 4 +- blockchain/mempool/mempool.go | 4 +- blockchain/mempool/mempool_test.go | 4 +- blockchain/miner_block.go | 16 +- blockchain/regpool/regpool.go | 148 +- blockchain/regpool/regpool_test.go | 4 +- blockchain/store.go | 2 +- blockchain/storetopo.go | 49 +- cmd/dero-wallet-cli/easymenu_post_open.go | 4 +- cmd/dero-wallet-cli/easymenu_pre_open.go | 9 +- cmd/dero-wallet-cli/main.go | 14 +- cmd/dero-wallet-cli/prompt.go | 16 +- cmd/derod/main.go | 212 +- cmd/derod/rpc_dero_getblocktemplate.go | 14 +- cmd/derod/websocket_server.go | 50 +- cmd/explorer/templates.go | 2 +- config/config.go | 4 +- config/version.go | 2 +- crypto/bn256/curve.go | 94 +- crypto/bn256/curve_test.go | 66 + crypto/bn256/g1_serialization.go | 55 +- crypto/bn256/gfp_decl.go | 2 +- crypto/paymentid.go | 2 +- crypto/sha3/doc.go | 2 +- glue/rwc/rwc.go | 5 +- glue/rwc/rwc_nhyoor.go | 68 + p2p/connection_handler.go | 53 +- p2p/connection_pool.go | 50 +- p2p/handshake.go | 6 +- p2p/inventory_handler.go | 135 + p2p/object_request.go | 35 +- p2p/object_response.go | 24 + p2p/wire_structs.go | 13 +- vendor/github.com/coreos/bbolt/.gitignore | 5 - vendor/github.com/coreos/bbolt/LICENSE | 20 - vendor/github.com/coreos/bbolt/Makefile | 30 - vendor/github.com/coreos/bbolt/README.md | 928 - .../github.com/coreos/bbolt/allocate_test.go | 30 - vendor/github.com/coreos/bbolt/appveyor.yml | 18 - vendor/github.com/coreos/bbolt/bolt_386.go | 10 - vendor/github.com/coreos/bbolt/bolt_amd64.go | 10 - vendor/github.com/coreos/bbolt/bolt_arm.go | 28 - vendor/github.com/coreos/bbolt/bolt_arm64.go | 12 - vendor/github.com/coreos/bbolt/bolt_linux.go | 10 - .../github.com/coreos/bbolt/bolt_mips64x.go | 12 - vendor/github.com/coreos/bbolt/bolt_mipsx.go | 12 - .../github.com/coreos/bbolt/bolt_openbsd.go | 27 - vendor/github.com/coreos/bbolt/bolt_ppc.go | 12 - vendor/github.com/coreos/bbolt/bolt_ppc64.go | 12 - .../github.com/coreos/bbolt/bolt_ppc64le.go | 12 - vendor/github.com/coreos/bbolt/bolt_s390x.go | 12 - vendor/github.com/coreos/bbolt/bolt_unix.go | 94 - .../coreos/bbolt/bolt_unix_solaris.go | 89 - .../github.com/coreos/bbolt/bolt_windows.go | 145 - .../github.com/coreos/bbolt/boltsync_unix.go | 8 - vendor/github.com/coreos/bbolt/bucket.go | 775 - vendor/github.com/coreos/bbolt/bucket_test.go | 1959 -- .../github.com/coreos/bbolt/cmd/bolt/main.go | 2136 -- .../coreos/bbolt/cmd/bolt/main_test.go | 456 - vendor/github.com/coreos/bbolt/cursor.go | 396 - vendor/github.com/coreos/bbolt/cursor_test.go | 817 - vendor/github.com/coreos/bbolt/db.go | 1140 - vendor/github.com/coreos/bbolt/db_test.go | 1721 - vendor/github.com/coreos/bbolt/doc.go | 44 - vendor/github.com/coreos/bbolt/errors.go | 71 - vendor/github.com/coreos/bbolt/freelist.go | 333 - .../github.com/coreos/bbolt/freelist_test.go | 288 - vendor/github.com/coreos/bbolt/node.go | 604 - vendor/github.com/coreos/bbolt/node_test.go | 156 - vendor/github.com/coreos/bbolt/page.go | 197 - vendor/github.com/coreos/bbolt/page_test.go | 72 - vendor/github.com/coreos/bbolt/quick_test.go | 87 - .../bbolt/simulation_no_freelist_sync_test.go | 47 - .../coreos/bbolt/simulation_test.go | 336 - vendor/github.com/coreos/bbolt/tx.go | 707 - vendor/github.com/coreos/bbolt/tx_test.go | 869 - .../github.com/deroproject/graviton/const.go | 16 +- .../github.com/deroproject/graviton/cursor.go | 4 - .../github.com/deroproject/graviton/extra.go | 107 +- .../github.com/deroproject/graviton/graph.go | 107 +- .../deroproject/graviton/node_inner.go | 4 +- .../deroproject/graviton/snapshot.go | 45 +- .../deroproject/graviton/snapshot_test.go | 171 +- .../deroproject/graviton/special.go | 52 +- .../github.com/deroproject/graviton/store.go | 100 +- .../deroproject/graviton/store_test.go | 31 +- .../github.com/deroproject/graviton/tree.go | 40 +- .../deroproject/graviton/tree_test.go | 66 +- vendor/github.com/intel-go/cpuid/.gitignore | 28 - vendor/github.com/intel-go/cpuid/LICENSE | 28 - vendor/github.com/intel-go/cpuid/README.md | 244 - vendor/github.com/intel-go/cpuid/cpuid.go | 1122 - .../intel-go/cpuid/cpuidlow_amd64.s | 24 - .../intel-go/cpuid/example/example.go | 68 - vendor/github.com/intel-go/fastjson/LICENSE | 28 - vendor/github.com/intel-go/fastjson/README.md | 43 - .../intel-go/fastjson/bench_test.go | 310 - vendor/github.com/intel-go/fastjson/decode.go | 1114 - .../intel-go/fastjson/decode_test.go | 1486 - vendor/github.com/intel-go/fastjson/encode.go | 1199 - .../intel-go/fastjson/encode_test.go | 538 - .../intel-go/fastjson/example_test.go | 252 - vendor/github.com/intel-go/fastjson/fold.go | 143 - .../github.com/intel-go/fastjson/fold_test.go | 116 - vendor/github.com/intel-go/fastjson/indent.go | 141 - .../intel-go/fastjson/number_test.go | 133 - .../github.com/intel-go/fastjson/scanner.go | 1031 - .../intel-go/fastjson/scanner_test.go | 280 - vendor/github.com/intel-go/fastjson/stream.go | 489 - .../intel-go/fastjson/stream_test.go | 354 - .../intel-go/fastjson/tagkey_test.go | 115 - vendor/github.com/intel-go/fastjson/tags.go | 44 - .../github.com/intel-go/fastjson/tags_test.go | 28 - .../intel-go/fastjson/testdata/canada.json.gz | Bin 599506 -> 0 bytes .../intel-go/fastjson/testdata/code.json.gz | Bin 120432 -> 0 bytes .../fastjson/testdata/large-dict.json.gz | Bin 5570045 -> 0 bytes .../fastjson/testdata/medium-dict.json.gz | Bin 1298074 -> 0 bytes .../klauspost/compress/flate/deflate.go | 821 + .../klauspost/compress/flate/deflate_test.go | 658 + .../klauspost/compress/flate/dict_decoder.go | 184 + .../compress/flate/dict_decoder_test.go | 139 + .../klauspost/compress/flate/fast_encoder.go | 254 + .../klauspost/compress/flate/flate_test.go | 360 + .../klauspost/compress/flate/gen.go | 265 + .../klauspost/compress/flate/gen_inflate.go | 294 + .../compress/flate/huffman_bit_writer.go | 911 + .../compress/flate/huffman_bit_writer_test.go | 382 + .../klauspost/compress/flate/huffman_code.go | 363 + .../compress/flate/huffman_sortByFreq.go | 178 + .../compress/flate/huffman_sortByLiteral.go | 201 + .../klauspost/compress/flate/inflate.go | 1010 + .../klauspost/compress/flate/inflate_gen.go | 1002 + .../klauspost/compress/flate/inflate_test.go | 282 + .../klauspost/compress/flate/level1.go | 179 + .../klauspost/compress/flate/level2.go | 205 + .../klauspost/compress/flate/level3.go | 229 + .../klauspost/compress/flate/level4.go | 212 + .../klauspost/compress/flate/level5.go | 279 + .../klauspost/compress/flate/level6.go | 282 + .../klauspost/compress/flate/reader_test.go | 106 + .../klauspost/compress/flate/regmask_amd64.go | 37 + .../klauspost/compress/flate/regmask_other.go | 39 + .../klauspost/compress/flate/stateless.go | 297 + .../testdata/huffman-null-max.dyn.expect | Bin 0 -> 101 bytes .../huffman-null-max.dyn.expect-noinput | Bin 0 -> 101 bytes .../flate/testdata/huffman-null-max.golden | Bin 0 -> 8219 bytes .../flate/testdata/huffman-null-max.in | Bin 0 -> 65535 bytes .../testdata/huffman-null-max.sync.expect | Bin 0 -> 78 bytes .../huffman-null-max.sync.expect-noinput | Bin 0 -> 78 bytes .../flate/testdata/huffman-null-max.wb.expect | Bin 0 -> 78 bytes .../huffman-null-max.wb.expect-noinput | Bin 0 -> 78 bytes .../flate/testdata/huffman-pi.dyn.expect | Bin 0 -> 1751 bytes .../testdata/huffman-pi.dyn.expect-noinput | Bin 0 -> 1751 bytes .../compress/flate/testdata/huffman-pi.golden | Bin 0 -> 1626 bytes .../compress/flate/testdata/huffman-pi.in | 1 + .../flate/testdata/huffman-pi.sync.expect | Bin 0 -> 1696 bytes .../testdata/huffman-pi.sync.expect-noinput | Bin 0 -> 1696 bytes .../flate/testdata/huffman-pi.wb.expect | Bin 0 -> 1696 bytes .../testdata/huffman-pi.wb.expect-noinput | Bin 0 -> 1696 bytes .../flate/testdata/huffman-rand-1k.dyn.expect | Bin 0 -> 1005 bytes .../huffman-rand-1k.dyn.expect-noinput | Bin 0 -> 1069 bytes .../flate/testdata/huffman-rand-1k.golden | Bin 0 -> 1005 bytes .../flate/testdata/huffman-rand-1k.in | Bin 0 -> 1000 bytes .../testdata/huffman-rand-1k.sync.expect | Bin 0 -> 1005 bytes .../huffman-rand-1k.sync.expect-noinput | Bin 0 -> 1054 bytes .../flate/testdata/huffman-rand-1k.wb.expect | Bin 0 -> 1005 bytes .../huffman-rand-1k.wb.expect-noinput | Bin 0 -> 1054 bytes .../testdata/huffman-rand-limit.dyn.expect | Bin 0 -> 252 bytes .../huffman-rand-limit.dyn.expect-noinput | 1 + .../flate/testdata/huffman-rand-limit.golden | Bin 0 -> 239 bytes .../flate/testdata/huffman-rand-limit.in | 4 + .../testdata/huffman-rand-limit.sync.expect | Bin 0 -> 229 bytes .../huffman-rand-limit.sync.expect-noinput | Bin 0 -> 229 bytes .../testdata/huffman-rand-limit.wb.expect | Bin 0 -> 186 bytes .../huffman-rand-limit.wb.expect-noinput | Bin 0 -> 186 bytes .../flate/testdata/huffman-rand-max.golden | Bin 0 -> 65540 bytes .../flate/testdata/huffman-rand-max.in | Bin 0 -> 65535 bytes .../flate/testdata/huffman-shifts.dyn.expect | Bin 0 -> 59 bytes .../huffman-shifts.dyn.expect-noinput | Bin 0 -> 59 bytes .../flate/testdata/huffman-shifts.golden | Bin 0 -> 1826 bytes .../compress/flate/testdata/huffman-shifts.in | 2 + .../flate/testdata/huffman-shifts.sync.expect | Bin 0 -> 32 bytes .../huffman-shifts.sync.expect-noinput | Bin 0 -> 32 bytes .../flate/testdata/huffman-shifts.wb.expect | Bin 0 -> 32 bytes .../testdata/huffman-shifts.wb.expect-noinput | Bin 0 -> 32 bytes .../testdata/huffman-text-shift.dyn.expect | Bin 0 -> 258 bytes .../huffman-text-shift.dyn.expect-noinput | 2 + .../flate/testdata/huffman-text-shift.golden | Bin 0 -> 252 bytes .../flate/testdata/huffman-text-shift.in | 14 + .../testdata/huffman-text-shift.sync.expect | Bin 0 -> 231 bytes .../huffman-text-shift.sync.expect-noinput | Bin 0 -> 231 bytes .../testdata/huffman-text-shift.wb.expect | Bin 0 -> 231 bytes .../huffman-text-shift.wb.expect-noinput | Bin 0 -> 231 bytes .../flate/testdata/huffman-text.dyn.expect | Bin 0 -> 304 bytes .../testdata/huffman-text.dyn.expect-noinput | 3 + .../flate/testdata/huffman-text.golden | Bin 0 -> 270 bytes .../compress/flate/testdata/huffman-text.in | 13 + .../flate/testdata/huffman-text.sync.expect | 1 + .../testdata/huffman-text.sync.expect-noinput | 1 + .../flate/testdata/huffman-text.wb.expect | 1 + .../testdata/huffman-text.wb.expect-noinput | 1 + .../flate/testdata/huffman-zero.dyn.expect | Bin 0 -> 313 bytes .../testdata/huffman-zero.dyn.expect-noinput | 1 + .../flate/testdata/huffman-zero.golden | Bin 0 -> 66 bytes .../compress/flate/testdata/huffman-zero.in | 1 + .../flate/testdata/huffman-zero.sync.expect | Bin 0 -> 17 bytes .../testdata/huffman-zero.sync.expect-noinput | Bin 0 -> 17 bytes .../flate/testdata/huffman-zero.wb.expect | Bin 0 -> 6 bytes .../testdata/huffman-zero.wb.expect-noinput | Bin 0 -> 6 bytes .../null-long-match.dyn.expect-noinput | Bin 0 -> 227 bytes .../null-long-match.sync.expect-noinput | Bin 0 -> 206 bytes .../null-long-match.wb.expect-noinput | Bin 0 -> 206 bytes .../compress/flate/testdata/regression.zip | Bin 0 -> 475404 bytes .../compress/flate/testdata/tokens.bin | 63 + .../klauspost/compress/flate/token.go | 375 + .../klauspost/compress/flate/token_test.go | 54 + .../klauspost/compress/flate/writer_test.go | 451 + vendor/github.com/sirupsen/logrus/.gitignore | 3 + .../github.com/sirupsen/logrus/.golangci.yml | 40 + vendor/github.com/sirupsen/logrus/.travis.yml | 22 +- .../github.com/sirupsen/logrus/CHANGELOG.md | 113 + vendor/github.com/sirupsen/logrus/README.md | 142 +- vendor/github.com/sirupsen/logrus/alt_exit.go | 18 +- .../sirupsen/logrus/alt_exit_test.go | 78 +- .../github.com/sirupsen/logrus/appveyor.yml | 28 +- .../github.com/sirupsen/logrus/buffer_pool.go | 52 + vendor/github.com/sirupsen/logrus/entry.go | 336 +- .../github.com/sirupsen/logrus/entry_test.go | 201 + .../sirupsen/logrus/example_basic_test.go | 12 +- .../logrus/example_custom_caller_test.go | 28 + .../example_default_field_value_test.go | 31 + .../sirupsen/logrus/example_function_test.go | 31 + .../logrus/example_global_hook_test.go | 37 + .../sirupsen/logrus/example_hook_test.go | 14 +- vendor/github.com/sirupsen/logrus/exported.go | 111 +- .../github.com/sirupsen/logrus/formatter.go | 51 +- vendor/github.com/sirupsen/logrus/go.mod | 10 + vendor/github.com/sirupsen/logrus/go.sum | 10 + .../github.com/sirupsen/logrus/hook_test.go | 76 +- .../sirupsen/logrus/hooks/syslog/syslog.go | 2 +- .../logrus/hooks/syslog/syslog_test.go | 2 + .../sirupsen/logrus/hooks/test/test.go | 20 +- .../sirupsen/logrus/hooks/test/test_test.go | 50 +- .../sirupsen/logrus/hooks/writer/README.md | 43 + .../sirupsen/logrus/hooks/writer/writer.go | 29 + .../logrus/hooks/writer/writer_test.go | 38 + .../logrus/internal/testutils/testutils.go | 58 + .../sirupsen/logrus/json_formatter.go | 78 +- .../sirupsen/logrus/json_formatter_test.go | 173 + .../github.com/sirupsen/logrus/level_test.go | 62 + vendor/github.com/sirupsen/logrus/logger.go | 301 +- .../sirupsen/logrus/logger_bench_test.go | 32 +- .../github.com/sirupsen/logrus/logger_test.go | 69 + vendor/github.com/sirupsen/logrus/logrus.go | 75 +- .../github.com/sirupsen/logrus/logrus_test.go | 489 +- .../sirupsen/logrus/terminal_bsd.go | 10 - .../sirupsen/logrus/terminal_check_bsd.go | 13 + .../sirupsen/logrus/terminal_check_js.go | 7 + .../logrus/terminal_check_no_terminal.go | 11 + .../logrus/terminal_check_notappengine.go | 6 +- .../sirupsen/logrus/terminal_check_solaris.go | 11 + .../sirupsen/logrus/terminal_check_unix.go | 13 + .../sirupsen/logrus/terminal_check_windows.go | 27 + .../sirupsen/logrus/terminal_linux.go | 14 - .../sirupsen/logrus/text_formatter.go | 240 +- .../sirupsen/logrus/text_formatter_test.go | 463 +- .../sirupsen/logrus/travis/cross_build.sh | 5 + .../sirupsen/logrus/travis/install.sh | 17 + .../github.com/sirupsen/logrus/travis/lint.sh | 7 + vendor/github.com/sirupsen/logrus/writer.go | 8 + .../github.com/sirupsen/logrus/writer_test.go | 34 + .../gitlab.com/nitya-sattva/go-x11/.directory | 6 - .../gitlab.com/nitya-sattva/go-x11/.gitignore | 1 - .../nitya-sattva/go-x11/.gitlab-ci.yml | 27 - .../nitya-sattva/go-x11/aesr/aesr.go | 316 - .../nitya-sattva/go-x11/aesr/aesr_test.go | 11 - .../nitya-sattva/go-x11/blake/blake.go | 352 - .../nitya-sattva/go-x11/blake/blake_test.go | 2170 -- .../gitlab.com/nitya-sattva/go-x11/bmw/bmw.go | 400 - .../nitya-sattva/go-x11/bmw/bmw_test.go | 2170 -- .../nitya-sattva/go-x11/cubed/cubed.go | 403 - .../nitya-sattva/go-x11/cubed/cubed_test.go | 2170 -- .../nitya-sattva/go-x11/echo/echo.go | 413 - .../nitya-sattva/go-x11/echo/echo_test.go | 2170 -- .../nitya-sattva/go-x11/groest/groest.go | 658 - .../nitya-sattva/go-x11/groest/groest_test.go | 2170 -- .../nitya-sattva/go-x11/hash/digest.go | 13 - .../nitya-sattva/go-x11/hash/digest_test.go | 11 - .../nitya-sattva/go-x11/hash/hash.go | 28 - .../nitya-sattva/go-x11/hash/hash_test.go | 11 - .../nitya-sattva/go-x11/jhash/jhash.go | 541 - .../nitya-sattva/go-x11/jhash/jhash_test.go | 2170 -- .../nitya-sattva/go-x11/keccak/keccak.go | 451 - .../nitya-sattva/go-x11/keccak/keccak_test.go | 2170 -- .../gitlab.com/nitya-sattva/go-x11/license.md | 15 - .../nitya-sattva/go-x11/luffa/luffa.go | 1840 -- .../nitya-sattva/go-x11/luffa/luffa_test.go | 2170 -- .../nitya-sattva/go-x11/nist/nist.go | 26342 ---------------- .../nitya-sattva/go-x11/nist/nist_test.go | 46 - .../gitlab.com/nitya-sattva/go-x11/readme.md | 36 - .../nitya-sattva/go-x11/shavite/shavite.go | 384 - .../go-x11/shavite/shavite_test.go | 2170 -- .../nitya-sattva/go-x11/simd/simd.go | 1920 -- .../nitya-sattva/go-x11/simd/simd_test.go | 2170 -- .../nitya-sattva/go-x11/skein/skein.go | 396 - .../nitya-sattva/go-x11/skein/skein_test.go | 2170 -- vendor/gitlab.com/nitya-sattva/go-x11/x11.go | 98 - .../nitya-sattva/go-x11/x11_test.go | 52 - vendor/nhooyr.io/websocket/.github/CODEOWNERS | 1 + .../nhooyr.io/websocket/.github/FUNDING.yml | 1 + .../websocket/.github/workflows/ci.yaml | 39 + vendor/nhooyr.io/websocket/.gitignore | 1 + vendor/nhooyr.io/websocket/LICENSE.txt | 21 + vendor/nhooyr.io/websocket/README.md | 132 + vendor/nhooyr.io/websocket/accept.go | 370 + vendor/nhooyr.io/websocket/accept_js.go | 20 + vendor/nhooyr.io/websocket/accept_test.go | 414 + vendor/nhooyr.io/websocket/autobahn_test.go | 228 + vendor/nhooyr.io/websocket/ci/all.sh | 12 + .../websocket/ci/container/Dockerfile | 14 + vendor/nhooyr.io/websocket/ci/fmt.sh | 38 + vendor/nhooyr.io/websocket/ci/lint.sh | 16 + vendor/nhooyr.io/websocket/ci/test.sh | 25 + vendor/nhooyr.io/websocket/close.go | 76 + vendor/nhooyr.io/websocket/close_notjs.go | 211 + vendor/nhooyr.io/websocket/close_test.go | 207 + vendor/nhooyr.io/websocket/compress.go | 39 + vendor/nhooyr.io/websocket/compress_notjs.go | 181 + vendor/nhooyr.io/websocket/compress_test.go | 34 + vendor/nhooyr.io/websocket/conn.go | 13 + vendor/nhooyr.io/websocket/conn_notjs.go | 265 + vendor/nhooyr.io/websocket/conn_test.go | 529 + vendor/nhooyr.io/websocket/dial.go | 292 + vendor/nhooyr.io/websocket/dial_test.go | 235 + vendor/nhooyr.io/websocket/doc.go | 32 + vendor/nhooyr.io/websocket/example_test.go | 198 + vendor/nhooyr.io/websocket/examples/README.md | 4 + .../websocket/examples/chat/README.md | 35 + .../nhooyr.io/websocket/examples/chat/chat.go | 182 + .../websocket/examples/chat/chat_test.go | 277 + .../websocket/examples/chat/index.css | 81 + .../websocket/examples/chat/index.html | 25 + .../websocket/examples/chat/index.js | 76 + .../nhooyr.io/websocket/examples/chat/main.go | 60 + .../websocket/examples/echo/README.md | 21 + .../nhooyr.io/websocket/examples/echo/main.go | 61 + .../websocket/examples/echo/server.go | 80 + .../websocket/examples/echo/server_test.go | 54 + vendor/nhooyr.io/websocket/export_test.go | 22 + vendor/nhooyr.io/websocket/frame.go | 294 + vendor/nhooyr.io/websocket/frame_test.go | 192 + vendor/nhooyr.io/websocket/go.mod | 15 + vendor/nhooyr.io/websocket/go.sum | 64 + .../websocket/internal/bpool/bpool.go | 24 + .../nhooyr.io/websocket/internal/errd/wrap.go | 14 + .../websocket/internal/test/assert/assert.go | 56 + .../nhooyr.io/websocket/internal/test/doc.go | 2 + .../websocket/internal/test/wstest/echo.go | 90 + .../websocket/internal/test/wstest/pipe.go | 66 + .../websocket/internal/test/xrand/xrand.go | 47 + .../websocket/internal/wsjs/wsjs_js.go | 170 + .../nhooyr.io/websocket/internal/xsync/go.go | 25 + .../websocket/internal/xsync/go_test.go | 18 + .../websocket/internal/xsync/int64.go | 23 + vendor/nhooyr.io/websocket/netconn.go | 166 + vendor/nhooyr.io/websocket/read.go | 471 + vendor/nhooyr.io/websocket/stringer.go | 91 + vendor/nhooyr.io/websocket/write.go | 397 + vendor/nhooyr.io/websocket/ws_js.go | 379 + vendor/nhooyr.io/websocket/ws_js_test.go | 38 + vendor/nhooyr.io/websocket/wsjson/wsjson.go | 67 + vendor/nhooyr.io/websocket/wspb/wspb.go | 73 + walletapi/balance_decoder.go | 79 +- walletapi/cipher.go | 4 +- walletapi/daemon_communication.go | 313 +- walletapi/daemon_connectivity.go | 134 + walletapi/daemon_connectivity_loop.go | 69 + walletapi/daemon_connectivity_wasm.go | 146 + walletapi/db.go | 331 +- walletapi/db_memory.go | 334 + walletapi/key_to_key.go | 33 - walletapi/mnemonics/mnemonics.go | 21 +- walletapi/rpc_transfersplit.go | 132 - walletapi/rpcserver.go | 242 - .../{ => rpcserver}/rpc_get_bulk_payments.go | 41 +- .../rpc_get_transfer_by_txid.go | 42 +- walletapi/{ => rpcserver}/rpc_getaddress.go | 20 +- walletapi/{ => rpcserver}/rpc_getbalance.go | 24 +- walletapi/{ => rpcserver}/rpc_getheight.go | 23 +- walletapi/{ => rpcserver}/rpc_gettransfers.go | 54 +- .../rpc_make_integrated_address.go | 36 +- walletapi/{ => rpcserver}/rpc_query_key.go | 35 +- .../rpc_split_integrated_address.go | 39 +- walletapi/{ => rpcserver}/rpc_transfer.go | 71 +- walletapi/rpcserver/rpc_websocket_server.go | 258 + walletapi/wallet.go | 155 +- walletapi/wallet_pool.go | 73 + walletapi/wallet_transfer.go | 10 +- 401 files changed, 23631 insertions(+), 85412 deletions(-) create mode 100644 crypto/bn256/curve_test.go create mode 100644 glue/rwc/rwc_nhyoor.go create mode 100644 p2p/inventory_handler.go delete mode 100644 vendor/github.com/coreos/bbolt/.gitignore delete mode 100644 vendor/github.com/coreos/bbolt/LICENSE delete mode 100644 vendor/github.com/coreos/bbolt/Makefile delete mode 100644 vendor/github.com/coreos/bbolt/README.md delete mode 100644 vendor/github.com/coreos/bbolt/allocate_test.go delete mode 100644 vendor/github.com/coreos/bbolt/appveyor.yml delete mode 100644 vendor/github.com/coreos/bbolt/bolt_386.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_amd64.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_arm.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_arm64.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_linux.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_mips64x.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_mipsx.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_openbsd.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_ppc.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_ppc64.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_ppc64le.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_s390x.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_unix.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_unix_solaris.go delete mode 100644 vendor/github.com/coreos/bbolt/bolt_windows.go delete mode 100644 vendor/github.com/coreos/bbolt/boltsync_unix.go delete mode 100644 vendor/github.com/coreos/bbolt/bucket.go delete mode 100644 vendor/github.com/coreos/bbolt/bucket_test.go delete mode 100644 vendor/github.com/coreos/bbolt/cmd/bolt/main.go delete mode 100644 vendor/github.com/coreos/bbolt/cmd/bolt/main_test.go delete mode 100644 vendor/github.com/coreos/bbolt/cursor.go delete mode 100644 vendor/github.com/coreos/bbolt/cursor_test.go delete mode 100644 vendor/github.com/coreos/bbolt/db.go delete mode 100644 vendor/github.com/coreos/bbolt/db_test.go delete mode 100644 vendor/github.com/coreos/bbolt/doc.go delete mode 100644 vendor/github.com/coreos/bbolt/errors.go delete mode 100644 vendor/github.com/coreos/bbolt/freelist.go delete mode 100644 vendor/github.com/coreos/bbolt/freelist_test.go delete mode 100644 vendor/github.com/coreos/bbolt/node.go delete mode 100644 vendor/github.com/coreos/bbolt/node_test.go delete mode 100644 vendor/github.com/coreos/bbolt/page.go delete mode 100644 vendor/github.com/coreos/bbolt/page_test.go delete mode 100644 vendor/github.com/coreos/bbolt/quick_test.go delete mode 100644 vendor/github.com/coreos/bbolt/simulation_no_freelist_sync_test.go delete mode 100644 vendor/github.com/coreos/bbolt/simulation_test.go delete mode 100644 vendor/github.com/coreos/bbolt/tx.go delete mode 100644 vendor/github.com/coreos/bbolt/tx_test.go delete mode 100644 vendor/github.com/intel-go/cpuid/.gitignore delete mode 100644 vendor/github.com/intel-go/cpuid/LICENSE delete mode 100644 vendor/github.com/intel-go/cpuid/README.md delete mode 100644 vendor/github.com/intel-go/cpuid/cpuid.go delete mode 100644 vendor/github.com/intel-go/cpuid/cpuidlow_amd64.s delete mode 100644 vendor/github.com/intel-go/cpuid/example/example.go delete mode 100644 vendor/github.com/intel-go/fastjson/LICENSE delete mode 100644 vendor/github.com/intel-go/fastjson/README.md delete mode 100644 vendor/github.com/intel-go/fastjson/bench_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/decode.go delete mode 100644 vendor/github.com/intel-go/fastjson/decode_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/encode.go delete mode 100644 vendor/github.com/intel-go/fastjson/encode_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/example_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/fold.go delete mode 100644 vendor/github.com/intel-go/fastjson/fold_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/indent.go delete mode 100644 vendor/github.com/intel-go/fastjson/number_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/scanner.go delete mode 100644 vendor/github.com/intel-go/fastjson/scanner_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/stream.go delete mode 100644 vendor/github.com/intel-go/fastjson/stream_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/tagkey_test.go delete mode 100644 vendor/github.com/intel-go/fastjson/tags.go delete mode 100644 vendor/github.com/intel-go/fastjson/tags_test.go delete mode 100755 vendor/github.com/intel-go/fastjson/testdata/canada.json.gz delete mode 100644 vendor/github.com/intel-go/fastjson/testdata/code.json.gz delete mode 100644 vendor/github.com/intel-go/fastjson/testdata/large-dict.json.gz delete mode 100644 vendor/github.com/intel-go/fastjson/testdata/medium-dict.json.gz create mode 100644 vendor/github.com/klauspost/compress/flate/deflate.go create mode 100644 vendor/github.com/klauspost/compress/flate/deflate_test.go create mode 100644 vendor/github.com/klauspost/compress/flate/dict_decoder.go create mode 100644 vendor/github.com/klauspost/compress/flate/dict_decoder_test.go create mode 100644 vendor/github.com/klauspost/compress/flate/fast_encoder.go create mode 100644 vendor/github.com/klauspost/compress/flate/flate_test.go create mode 100644 vendor/github.com/klauspost/compress/flate/gen.go create mode 100644 vendor/github.com/klauspost/compress/flate/gen_inflate.go create mode 100644 vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go create mode 100644 vendor/github.com/klauspost/compress/flate/huffman_bit_writer_test.go create mode 100644 vendor/github.com/klauspost/compress/flate/huffman_code.go create mode 100644 vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go create mode 100644 vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go create mode 100644 vendor/github.com/klauspost/compress/flate/inflate.go create mode 100644 vendor/github.com/klauspost/compress/flate/inflate_gen.go create mode 100644 vendor/github.com/klauspost/compress/flate/inflate_test.go create mode 100644 vendor/github.com/klauspost/compress/flate/level1.go create mode 100644 vendor/github.com/klauspost/compress/flate/level2.go create mode 100644 vendor/github.com/klauspost/compress/flate/level3.go create mode 100644 vendor/github.com/klauspost/compress/flate/level4.go create mode 100644 vendor/github.com/klauspost/compress/flate/level5.go create mode 100644 vendor/github.com/klauspost/compress/flate/level6.go create mode 100644 vendor/github.com/klauspost/compress/flate/reader_test.go create mode 100644 vendor/github.com/klauspost/compress/flate/regmask_amd64.go create mode 100644 vendor/github.com/klauspost/compress/flate/regmask_other.go create mode 100644 vendor/github.com/klauspost/compress/flate/stateless.go create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-null-max.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-pi.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-1k.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-limit.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-max.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-rand-max.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-shifts.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text-shift.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-text.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.dyn.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.golden create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.in create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.sync.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.wb.expect create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/huffman-zero.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/null-long-match.dyn.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/null-long-match.sync.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/null-long-match.wb.expect-noinput create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/regression.zip create mode 100644 vendor/github.com/klauspost/compress/flate/testdata/tokens.bin create mode 100644 vendor/github.com/klauspost/compress/flate/token.go create mode 100644 vendor/github.com/klauspost/compress/flate/token_test.go create mode 100644 vendor/github.com/klauspost/compress/flate/writer_test.go create mode 100644 vendor/github.com/sirupsen/logrus/.golangci.yml create mode 100644 vendor/github.com/sirupsen/logrus/buffer_pool.go create mode 100644 vendor/github.com/sirupsen/logrus/example_custom_caller_test.go create mode 100644 vendor/github.com/sirupsen/logrus/example_default_field_value_test.go create mode 100644 vendor/github.com/sirupsen/logrus/example_function_test.go create mode 100644 vendor/github.com/sirupsen/logrus/example_global_hook_test.go create mode 100644 vendor/github.com/sirupsen/logrus/go.mod create mode 100644 vendor/github.com/sirupsen/logrus/go.sum create mode 100644 vendor/github.com/sirupsen/logrus/hooks/writer/README.md create mode 100644 vendor/github.com/sirupsen/logrus/hooks/writer/writer.go create mode 100644 vendor/github.com/sirupsen/logrus/hooks/writer/writer_test.go create mode 100644 vendor/github.com/sirupsen/logrus/internal/testutils/testutils.go create mode 100644 vendor/github.com/sirupsen/logrus/level_test.go create mode 100644 vendor/github.com/sirupsen/logrus/logger_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_bsd.go create mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_bsd.go create mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_js.go create mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go create mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_solaris.go create mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_unix.go create mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_windows.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_linux.go create mode 100755 vendor/github.com/sirupsen/logrus/travis/cross_build.sh create mode 100755 vendor/github.com/sirupsen/logrus/travis/install.sh create mode 100755 vendor/github.com/sirupsen/logrus/travis/lint.sh create mode 100644 vendor/github.com/sirupsen/logrus/writer_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/.directory delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/.gitignore delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/.gitlab-ci.yml delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/aesr/aesr.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/aesr/aesr_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/blake/blake.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/blake/blake_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/bmw/bmw.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/bmw/bmw_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/cubed/cubed.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/cubed/cubed_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/echo/echo.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/echo/echo_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/groest/groest.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/groest/groest_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/hash/digest.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/hash/digest_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/hash/hash.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/hash/hash_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/jhash/jhash.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/jhash/jhash_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/keccak/keccak.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/keccak/keccak_test.go delete mode 100755 vendor/gitlab.com/nitya-sattva/go-x11/license.md delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/luffa/luffa.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/luffa/luffa_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/nist/nist.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/nist/nist_test.go delete mode 100755 vendor/gitlab.com/nitya-sattva/go-x11/readme.md delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/shavite/shavite.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/shavite/shavite_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/simd/simd.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/simd/simd_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/skein/skein.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/skein/skein_test.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/x11.go delete mode 100644 vendor/gitlab.com/nitya-sattva/go-x11/x11_test.go create mode 100644 vendor/nhooyr.io/websocket/.github/CODEOWNERS create mode 100644 vendor/nhooyr.io/websocket/.github/FUNDING.yml create mode 100644 vendor/nhooyr.io/websocket/.github/workflows/ci.yaml create mode 100644 vendor/nhooyr.io/websocket/.gitignore create mode 100644 vendor/nhooyr.io/websocket/LICENSE.txt create mode 100644 vendor/nhooyr.io/websocket/README.md create mode 100644 vendor/nhooyr.io/websocket/accept.go create mode 100644 vendor/nhooyr.io/websocket/accept_js.go create mode 100644 vendor/nhooyr.io/websocket/accept_test.go create mode 100644 vendor/nhooyr.io/websocket/autobahn_test.go create mode 100755 vendor/nhooyr.io/websocket/ci/all.sh create mode 100644 vendor/nhooyr.io/websocket/ci/container/Dockerfile create mode 100755 vendor/nhooyr.io/websocket/ci/fmt.sh create mode 100755 vendor/nhooyr.io/websocket/ci/lint.sh create mode 100755 vendor/nhooyr.io/websocket/ci/test.sh create mode 100644 vendor/nhooyr.io/websocket/close.go create mode 100644 vendor/nhooyr.io/websocket/close_notjs.go create mode 100644 vendor/nhooyr.io/websocket/close_test.go create mode 100644 vendor/nhooyr.io/websocket/compress.go create mode 100644 vendor/nhooyr.io/websocket/compress_notjs.go create mode 100644 vendor/nhooyr.io/websocket/compress_test.go create mode 100644 vendor/nhooyr.io/websocket/conn.go create mode 100644 vendor/nhooyr.io/websocket/conn_notjs.go create mode 100644 vendor/nhooyr.io/websocket/conn_test.go create mode 100644 vendor/nhooyr.io/websocket/dial.go create mode 100644 vendor/nhooyr.io/websocket/dial_test.go create mode 100644 vendor/nhooyr.io/websocket/doc.go create mode 100644 vendor/nhooyr.io/websocket/example_test.go create mode 100644 vendor/nhooyr.io/websocket/examples/README.md create mode 100644 vendor/nhooyr.io/websocket/examples/chat/README.md create mode 100644 vendor/nhooyr.io/websocket/examples/chat/chat.go create mode 100644 vendor/nhooyr.io/websocket/examples/chat/chat_test.go create mode 100644 vendor/nhooyr.io/websocket/examples/chat/index.css create mode 100644 vendor/nhooyr.io/websocket/examples/chat/index.html create mode 100644 vendor/nhooyr.io/websocket/examples/chat/index.js create mode 100644 vendor/nhooyr.io/websocket/examples/chat/main.go create mode 100644 vendor/nhooyr.io/websocket/examples/echo/README.md create mode 100644 vendor/nhooyr.io/websocket/examples/echo/main.go create mode 100644 vendor/nhooyr.io/websocket/examples/echo/server.go create mode 100644 vendor/nhooyr.io/websocket/examples/echo/server_test.go create mode 100644 vendor/nhooyr.io/websocket/export_test.go create mode 100644 vendor/nhooyr.io/websocket/frame.go create mode 100644 vendor/nhooyr.io/websocket/frame_test.go create mode 100644 vendor/nhooyr.io/websocket/go.mod create mode 100644 vendor/nhooyr.io/websocket/go.sum create mode 100644 vendor/nhooyr.io/websocket/internal/bpool/bpool.go create mode 100644 vendor/nhooyr.io/websocket/internal/errd/wrap.go create mode 100644 vendor/nhooyr.io/websocket/internal/test/assert/assert.go create mode 100644 vendor/nhooyr.io/websocket/internal/test/doc.go create mode 100644 vendor/nhooyr.io/websocket/internal/test/wstest/echo.go create mode 100644 vendor/nhooyr.io/websocket/internal/test/wstest/pipe.go create mode 100644 vendor/nhooyr.io/websocket/internal/test/xrand/xrand.go create mode 100644 vendor/nhooyr.io/websocket/internal/wsjs/wsjs_js.go create mode 100644 vendor/nhooyr.io/websocket/internal/xsync/go.go create mode 100644 vendor/nhooyr.io/websocket/internal/xsync/go_test.go create mode 100644 vendor/nhooyr.io/websocket/internal/xsync/int64.go create mode 100644 vendor/nhooyr.io/websocket/netconn.go create mode 100644 vendor/nhooyr.io/websocket/read.go create mode 100644 vendor/nhooyr.io/websocket/stringer.go create mode 100644 vendor/nhooyr.io/websocket/write.go create mode 100644 vendor/nhooyr.io/websocket/ws_js.go create mode 100644 vendor/nhooyr.io/websocket/ws_js_test.go create mode 100644 vendor/nhooyr.io/websocket/wsjson/wsjson.go create mode 100644 vendor/nhooyr.io/websocket/wspb/wspb.go create mode 100644 walletapi/daemon_connectivity.go create mode 100644 walletapi/daemon_connectivity_loop.go create mode 100644 walletapi/daemon_connectivity_wasm.go create mode 100644 walletapi/db_memory.go delete mode 100644 walletapi/key_to_key.go delete mode 100644 walletapi/rpc_transfersplit.go delete mode 100644 walletapi/rpcserver.go rename walletapi/{ => rpcserver}/rpc_get_bulk_payments.go (65%) rename walletapi/{ => rpcserver}/rpc_get_transfer_by_txid.go (63%) rename walletapi/{ => rpcserver}/rpc_getaddress.go (75%) rename walletapi/{ => rpcserver}/rpc_getbalance.go (75%) rename walletapi/{ => rpcserver}/rpc_getheight.go (75%) rename walletapi/{ => rpcserver}/rpc_gettransfers.go (61%) rename walletapi/{ => rpcserver}/rpc_make_integrated_address.go (61%) rename walletapi/{ => rpcserver}/rpc_query_key.go (65%) rename walletapi/{ => rpcserver}/rpc_split_integrated_address.go (55%) rename walletapi/{ => rpcserver}/rpc_transfer.go (61%) create mode 100644 walletapi/rpcserver/rpc_websocket_server.go create mode 100644 walletapi/wallet_pool.go diff --git a/astrobwt/astrobwt.go b/astrobwt/astrobwt.go index 7ae0c2a..bcc45d2 100644 --- a/astrobwt/astrobwt.go +++ b/astrobwt/astrobwt.go @@ -144,7 +144,7 @@ func POW(inputdata []byte) (outputhash [32]byte) { stage2_result, eos := BWT(stage2[:stage2_length]) // fmt.Printf("result %x stage2_length %d \n", key, stage2_length) - copy(stage2_result[:],[]byte("Broken for testnet")) + copy(stage2_result[:], []byte("Broken for testnet")) key = sha3.Sum256(stage2_result) //fmt.Printf("result %x\n", key) @@ -222,10 +222,9 @@ func POW_0alloc(inputdata []byte) (outputhash [32]byte) { eos = BWT_0alloc(stage2[:stage2_length], sa[:stage2_length+1], stage2_result[:stage2_length+1]) _ = eos - copy(stage2_result[:],[]byte("Broken for testnet")) + copy(stage2_result[:], []byte("Broken for testnet")) key = sha3.Sum256(stage2_result[:stage2_length+1]) - copy(outputhash[:], key[:]) return } diff --git a/astrobwt/astrobwt_optimized.go b/astrobwt/astrobwt_optimized.go index 7c60ade..8b6dba2 100644 --- a/astrobwt/astrobwt_optimized.go +++ b/astrobwt/astrobwt_optimized.go @@ -66,7 +66,7 @@ func POW_optimized_v2(inputdata []byte, max_limit int, data *Data) (outputhash [ salsa.XORKeyStream(data.stage2[1:stage2_length+1], data.stage2[1:stage2_length+1], &counter, &key) sort_indices(stage2_length+1, data.stage2[:], data.stage2_result[:], data) - copy(data.stage2_result[:],[]byte("Broken for testnet")) + copy(data.stage2_result[:], []byte("Broken for testnet")) key = sha3.Sum256(data.stage2_result[:stage2_length+1]) for i := range data.stage2 { data.stage2[i] = 0 diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 3852ade..42d529b 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -105,6 +105,9 @@ type Blockchain struct { P2P_Block_Relayer func(*block.Complete_Block, uint64) // tell p2p to broadcast any block this daemon hash found + RPC_NotifyNewBlock *sync.Cond // used to notify rpc that a new block has been found + RPC_NotifyHeightChanged *sync.Cond // used to notify rpc that chain height has changed due to addition of block + sync.RWMutex } @@ -152,6 +155,9 @@ func Blockchain_Start(params map[string]interface{}) (*Blockchain, error) { chain.Mempool, err = mempool.Init_Mempool(params) chain.Regpool, err = regpool.Init_Regpool(params) + chain.RPC_NotifyNewBlock = sync.NewCond(&sync.Mutex{}) // used by dero daemon to notify all websockets that new block has arrived + chain.RPC_NotifyHeightChanged = sync.NewCond(&sync.Mutex{}) // used by dero daemon to notify all websockets that chain height has changed + if !chain.Store.IsBalancesIntialized() { logger.Debugf("Genesis block not in store, add it now") var complete_block block.Complete_Block @@ -273,6 +279,7 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro chain.Lock() defer chain.Unlock() result = false + height_changed := false chain.MINING_BLOCK = true @@ -320,6 +327,17 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro } }() + // notify everyone who needs to know that a new block is in the chain + chain.RPC_NotifyNewBlock.L.Lock() + chain.RPC_NotifyNewBlock.Broadcast() + chain.RPC_NotifyNewBlock.L.Unlock() + + if height_changed { + chain.RPC_NotifyHeightChanged.L.Lock() + chain.RPC_NotifyHeightChanged.Broadcast() + chain.RPC_NotifyHeightChanged.L.Unlock() + } + //dbtx.Sync() // sync the DB to disk after every execution of this function //if old_top != chain.Load_TOP_ID() { // if top has changed, discard mining templates and start afresh @@ -350,7 +368,7 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro for k := range chain.Tips { if block_hash == k { block_logger.Debugf("block already in chain skipping it ") - return errormsg.ErrAlreadyExists, false + return errormsg.ErrAlreadyExists, false } } @@ -407,7 +425,7 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro // the block timestamp cannot be less than any of the parents for i := range bl.Tips { if chain.Load_Block_Timestamp(bl.Tips[i]) > bl.Timestamp { - block_logger.Warnf("Block timestamp is less than its parent, rejecting block %x ",bl.Serialize() ) + block_logger.Warnf("Block timestamp is less than its parent, rejecting block %x ", bl.Serialize()) return errormsg.ErrInvalidTimestamp, false } } @@ -415,7 +433,7 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro //logger.Infof("current version %d height %d", chain.Get_Current_Version_at_Height( 2500), chain.Calculate_Height_At_Tips(dbtx, bl.Tips)) // check whether the major version ( hard fork) is valid if !chain.Check_Block_Version(bl) { - block_logger.Warnf("Rejecting !! Block has invalid fork version actual %d expected %d", bl.Major_Version, chain.Get_Current_Version_at_Height(chain.Calculate_Height_At_Tips( bl.Tips))) + block_logger.Warnf("Rejecting !! Block has invalid fork version actual %d expected %d", bl.Major_Version, chain.Get_Current_Version_at_Height(chain.Calculate_Height_At_Tips(bl.Tips))) return errormsg.ErrInvalidBlock, false } @@ -631,6 +649,8 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro if height > chain.Get_Height() || height == 0 { // exception for genesis block atomic.StoreInt64(&chain.Height, height) //chain.Store_TOP_HEIGHT(dbtx, height) + + height_changed = true rlog.Infof("Chain extended new height %d blid %s", chain.Height, block_hash) } else { @@ -677,7 +697,7 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro base_topo_index := chain.Load_Block_Topological_order(base) // we will directly use graviton to mov in to history - rlog.Infof("Full order %+v base %s base topo pos %d", full_order, base, base_topo_index) + rlog.Debugf("Full order %+v base %s base topo pos %d", full_order, base, base_topo_index) if len(bl.Tips) == 0 { base_topo_index = 0 @@ -689,19 +709,23 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro // check whether the new block is at the same position at the last position current_topo_block := i + base_topo_index - if skip && current_topo_block < chain.Store.Topo_store.Count() { - toporecord, err := chain.Store.Topo_store.Read(current_topo_block) - if err != nil { - panic(err) - } - if full_order[i] == toporecord.BLOCK_ID { // skip reprocessing if not required - continue + previous_topo_block := current_topo_block - 1 + if skip { + if current_topo_block < chain.Store.Topo_store.Count() { + toporecord, err := chain.Store.Topo_store.Read(current_topo_block) + if err != nil { + panic(err) + } + if full_order[i] == toporecord.BLOCK_ID { // skip reprocessing if not required + continue + } } skip = false // if one block processed, process every higher block - } + rlog.Debugf("will execute order from %d %s", i, full_order[i]) + // TODO we must run smart contracts and TXs in this order // basically client protocol must run here // even if the HF has triggered we may still accept, old blocks for some time @@ -726,71 +750,22 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro // generate miner TX rewards as per client protocol if hard_fork_version_current == 1 { - //CommitElGamal - /* - - // hf 2 or later generate miner TX rewards as per client protocol - - past_coins_generated := chain.Load_Already_Generated_Coins_for_Topo_Index(dbtx, highest_topo-1) - - base_reward := emission.GetBlockReward_Atlantis(hard_fork_version_current, past_coins_generated) - - // base reward is only 90%, rest 10 % is pushed back - if globals.IsMainnet(){ - base_reward = (base_reward * 9) / 10 - } - - // lower reward for byzantine behaviour - // for as many block as added - if chain.isblock_SideBlock(dbtx, bl_current_hash, highest_topo) { // lost race (or byzantine behaviour) - if hard_fork_version_current == 2 { - base_reward = (base_reward * 67) / 100 // give only 67 % reward - }else{ - base_reward = (base_reward * 8) / 100 // give only 8 % reward - } - } - - // logger.Infof("past coins generated %d base reward %d", past_coins_generated, base_reward) - - // the total reward must be given to the miner TX, since it contains 0, we patch only the output - // and leave the original TX untouched - total_reward := base_reward + total_fees - - // store total reward - dbtx.StoreUint64(BLOCKCHAIN_UNIVERSE, GALAXY_BLOCK, bl_current_hash[:], PLANET_MINERTX_REWARD, total_reward) - - // store base reward - dbtx.StoreUint64(BLOCKCHAIN_UNIVERSE, GALAXY_BLOCK, bl_current_hash[:], PLANET_BASEREWARD, base_reward) - - // store total generated coins - dbtx.StoreUint64(BLOCKCHAIN_UNIVERSE, GALAXY_BLOCK, bl_current_hash[:], PLANET_ALREADY_GENERATED_COINS, past_coins_generated+base_reward) - - //logger.Infof("base reward %s total generated %s",globals.FormatMoney12(base_reward), globals.FormatMoney12(past_coins_generated+base_reward)) - */ - } var balance_tree *graviton.Tree // if bl_current.Height == 0 { // if it's genesis block - ss, err := chain.Store.Balance_store.LoadSnapshot(0) - if err != nil { + if ss, err := chain.Store.Balance_store.LoadSnapshot(0); err != nil { panic(err) - } - - balance_tree, err = ss.GetTree(BALANCE_TREE) - if err != nil { + } else if balance_tree, err = ss.GetTree(BALANCE_TREE); err != nil { panic(err) } } else { // we already have a block before us, use it - previous_topo_block := i + base_topo_index - 1 record_version := uint64(0) - if previous_topo_block >= 0 { toporecord, err := chain.Store.Topo_store.Read(previous_topo_block) - //fmt.Printf("current block %d previous topo %d record %+v err %s\n", i+base_topo_index, i+base_topo_index-1, toporecord,err) if err != nil { panic(err) } @@ -806,7 +781,6 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro if err != nil { panic(err) } - } fees_collected := uint64(0) @@ -816,29 +790,21 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro // their transactions are ignored //chain.Store.Topo_store.Write(i+base_topo_index, full_order[i],0, int64(bl_current.Height)) // write entry so as sideblock could work - if !chain.isblock_SideBlock_internal(full_order[i], i+base_topo_index, int64(bl_current.Height)) { - + if !chain.isblock_SideBlock_internal(full_order[i], current_topo_block, int64(bl_current.Height)) { for _, txhash := range bl_current.Tx_hashes { // execute all the transactions - if tx_bytes, err := chain.Store.Block_tx_store.ReadTX(txhash); err != nil { panic(err) } else { - var tx transaction.Transaction if err = tx.DeserializeHeader(tx_bytes); err != nil { panic(err) } - // we have loaded a tx successfully, now lets execute it fees_collected += chain.process_transaction(tx, balance_tree) } - } - chain.process_miner_transaction(bl_current.Miner_TX, bl_current.Height == 0, balance_tree, fees_collected) - - } else { rlog.Debugf("this block is a side block block height %d blid %s ", chain.Load_Block_Height(full_order[i]), full_order[i]) @@ -850,9 +816,8 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro panic(err) } - chain.Store.Topo_store.Write(i+base_topo_index, full_order[i], commit_version, chain.Load_Block_Height(full_order[i])) - - rlog.Debugf("%d %s topo_index %d base topo %d", i, full_order[i], i+base_topo_index, base_topo_index) + chain.Store.Topo_store.Write(current_topo_block, full_order[i], commit_version, chain.Load_Block_Height(full_order[i])) + rlog.Debugf("%d %s topo_index %d base topo %d", i, full_order[i], current_topo_block, base_topo_index) // this tx must be stored, linked with this block @@ -896,7 +861,7 @@ func (chain *Blockchain) Add_Complete_Block(cbl *block.Complete_Block) (err erro } } - rlog.Infof("New tips(after adding %s) %+v", bl.GetHash(), new_tips) + rlog.Debugf("New tips(after adding %s) %+v", bl.GetHash(), new_tips) chain.Tips = new_tips } @@ -1129,6 +1094,7 @@ var block_processing_time = prometheus.NewHistogram(prometheus.HistogramOpts{ // verifying everything means everything possible // this only change mempool, no DB changes func (chain *Blockchain) Add_TX_To_Pool(tx *transaction.Transaction) (result bool) { + var err error if tx.IsRegistration() { // registration tx will not go any forward // ggive regpool a chance to register if ss, err := chain.Store.Balance_store.LoadSnapshot(0); err == nil { @@ -1153,13 +1119,25 @@ func (chain *Blockchain) Add_TX_To_Pool(tx *transaction.Transaction) (result boo return false } + chain_height := uint64(chain.Get_Height()) + if chain_height > tx.Height { + rlog.Tracef(2, "TX %s rejected since chain has already progressed", txhash) + return false + } + // quick check without calculating everything whether tx is in pool, if yes we do nothing if chain.Mempool.Mempool_TX_Exist(txhash) { rlog.Tracef(2, "TX %s rejected Already in MEMPOOL", txhash) - return true + return false } - hf_version := chain.Get_Current_Version_at_Height(chain.Get_Height()) + // check whether tx is already mined + if _, err = chain.Store.Block_tx_store.ReadTX(txhash); err == nil { + rlog.Tracef(2, "TX %s rejected Already mined in some block", txhash) + return false + } + + hf_version := chain.Get_Current_Version_at_Height(int64(chain_height)) // if TX is too big, then it cannot be mined due to fixed block size, reject such TXs here // currently, limits are as per consensus @@ -1270,7 +1248,7 @@ func (chain *Blockchain) SortTips(tips []crypto.Hash) (sorted []crypto.Hash) { // if block height is less than or equal to height of past 3*config.STABLE_LIMIT topographical blocks // this is part of consensus rule // this is the topoheight of this block itself -func (chain *Blockchain) isblock_SideBlock(blid crypto.Hash) bool { +func (chain *Blockchain) Isblock_SideBlock(blid crypto.Hash) bool { block_topoheight := chain.Load_Block_Topological_order(blid) if block_topoheight == 0 { return false @@ -1339,7 +1317,7 @@ func (chain *Blockchain) IS_TX_Valid(txhash crypto.Hash) (valid_blid crypto.Hash } for _, blid := range exist_list { - if chain.isblock_SideBlock(blid) { + if chain.Isblock_SideBlock(blid) { invalid_blid = append(invalid_blid, blid) } else { valid_blid = blid @@ -1502,6 +1480,10 @@ func (chain *Blockchain) Rewind_Chain(rewind_count int) (result bool) { // TODO we must fix safeness using the stable calculation + if rewind_count == 0 { + return + } + top_block_topo_index := chain.Load_TOPO_HEIGHT() rewinded := int64(0) @@ -1511,8 +1493,6 @@ func (chain *Blockchain) Rewind_Chain(rewind_count int) (result bool) { } rewinded++ - - fmt.Printf("rewing 1 block top loop") } for { // rewinf till we reach a safe point @@ -1525,7 +1505,6 @@ func (chain *Blockchain) Rewind_Chain(rewind_count int) (result bool) { break } - fmt.Printf("rewing 1 block bottom loop %v %+v rewinded %d\n", chain.IsBlockSyncBlockHeight(r.BLOCK_ID), r, rewinded) rewinded++ } @@ -2135,103 +2114,3 @@ func sliceExists(slice []crypto.Hash, hash crypto.Hash) bool { } return false } - -/* - - -var node_map = map[crypto.Hash]bool{} - -func collect_nodes(chain *Blockchain, dbtx storage.DBTX, blid crypto.Hash) { - future := chain.Get_Block_Future(dbtx, blid) - for i := range future { - //node_map[future[i]]=true - - if _, ok := node_map[future[i]]; !ok { - collect_nodes(chain, dbtx, future[i]) // recursive add node - } - } - - node_map[blid] = true - -} -*/ - -/* -func writenode(chain *Blockchain, dbtx storage.DBTX, w *bufio.Writer, blid crypto.Hash) { // process a node, recursively - - collect_nodes(chain, dbtx, blid) - - sync_blocks := map[crypto.Hash]uint64{} - - for k, _ := range node_map { - if chain.IsBlockSyncBlockHeight(dbtx, k) { - // sync_blocks = append(sync_blocks, - sync_blocks[k] = uint64(chain.Load_Height_for_BL_ID(dbtx, k)) - } - } - - w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) - for k := range node_map { - - //anticone := chain.Get_AntiCone_Unsettled(k) - - color := "white" - - if chain.IsBlockSyncBlockHeight(dbtx, k) { - color = "green" - } - - - - - //w.WriteString(fmt.Sprintf("L%s [ fillcolor=%s label = \"%s %d height %d score %d stored %d order %d\" ];\n", k.String(), color, k.String(), 0, chain.Load_Height_for_BL_ID(dbtx, k), cumulative_difficulty, chain.Load_Block_Cumulative_Difficulty(dbtx, k), chain.Load_Block_Topological_order(dbtx, k))) - w.WriteString(fmt.Sprintf("L%s [ fillcolor=%s label = \"%s %d height %d score %d stored %d order %d\" ];\n", k.String(), color, k.String(), 0, chain.Load_Height_for_BL_ID(dbtx, k), 0, chain.Load_Block_Cumulative_Difficulty(dbtx, k), chain.Load_Block_Topological_order(dbtx, k))) - } - w.WriteString(fmt.Sprintf("}\n")) - - // now dump the interconnections - for k := range node_map { - future := chain.Get_Block_Future(dbtx, k) - for i := range future { - w.WriteString(fmt.Sprintf("L%s -> L%s ;\n", k.String(), future[i].String())) - } - - } -} - -func WriteBlockChainTree(chain *Blockchain, filename string) (err error) { - - dbtx, err := chain.store.BeginTX(false) - if err != nil { - logger.Warnf("Could NOT add block to chain. Error opening writable TX, err %s", err) - return - } - - defer dbtx.Rollback() - - f, err := os.Create(filename) - if err != nil { - return - } - defer f.Close() - - w := bufio.NewWriter(f) - defer w.Flush() - w.WriteString("digraph dero_blockchain_graph { \n") - - blid, err := chain.Load_Block_Topological_order_at_index(nil, 158800) - if err != nil { - logger.Warnf("Cannot get block at topoheight %d err: %s", 158800, err) - return - } - - writenode(chain, dbtx, w, blid) - //g := Generate_Genesis_Block() - //writenode(chain, dbtx, w, g.GetHash()) - - w.WriteString("}\n") - - return -} - -*/ diff --git a/blockchain/blockheader.go b/blockchain/blockheader.go index fc52f8b..27b1533 100644 --- a/blockchain/blockheader.go +++ b/blockchain/blockheader.go @@ -20,7 +20,7 @@ package blockchain import "github.com/deroproject/derohe/crypto" import "github.com/deroproject/derohe/structures" -// this function is only used by the RPC and is not used by the core +// this function is only used by the RPC and is not used by the core and should be moved to RPC interface /* fill up the above structure from the blockchain */ func (chain *Blockchain) GetBlockHeader(hash crypto.Hash) (result structures.BlockHeader_Print, err error) { @@ -44,7 +44,7 @@ func (chain *Blockchain) GetBlockHeader(hash crypto.Hash) (result structures.Blo if result.TopoHeight >= chain.LocatePruneTopo()+10 { // this result may/may not be valid at just above prune heights result.SyncBlock = chain.IsBlockSyncBlockHeight(hash) } - result.SideBlock = chain.isblock_SideBlock(hash) + result.SideBlock = chain.Isblock_SideBlock(hash) //result.Reward = chain.Load_Block_Total_Reward(dbtx, hash) result.TXCount = int64(len(bl.Tx_hashes)) diff --git a/blockchain/mempool/mempool.go b/blockchain/mempool/mempool.go index 05fc00f..c90471b 100644 --- a/blockchain/mempool/mempool.go +++ b/blockchain/mempool/mempool.go @@ -281,15 +281,13 @@ func (pool *Mempool) Mempool_Add_TX(tx *transaction.Transaction, Height uint64) defer pool.Unlock() var object mempool_object - tx_hash := crypto.Hash(tx.GetHash()) + tx_hash := crypto.Hash(tx.GetHash()) if pool.Mempool_Keyimage_Spent(tx.Proof.Nonce()) { rlog.Debugf("Rejecting TX, since nonce already seen %x", tx_hash) return false } - - // check if tx already exists, skip it if _, ok := pool.txs.Load(tx_hash); ok { //rlog.Debugf("Pool already contains %s, skipping", tx_hash) diff --git a/blockchain/mempool/mempool_test.go b/blockchain/mempool/mempool_test.go index 96ba323..e6a63c0 100644 --- a/blockchain/mempool/mempool_test.go +++ b/blockchain/mempool/mempool_test.go @@ -103,13 +103,13 @@ func Test_mempool_Full_block_72_2c4738d3856e8e3e8f9fc4818a9197d4911af3010e067ec5 } // pool must have 1 key_image - + key_image_count := 0 pool.key_images.Range(func(k, value interface{}) bool { key_image_count++ return true }) - + if key_image_count != 1 { t.Errorf("Pool doesnot have necessary key image") } diff --git a/blockchain/miner_block.go b/blockchain/miner_block.go index d58b41b..17cd685 100644 --- a/blockchain/miner_block.go +++ b/blockchain/miner_block.go @@ -100,12 +100,12 @@ func (chain *Blockchain) Create_new_miner_block(miner_address address.Address, t if len(bl.Tips) >= 3 { break } - if !chain.verifyNonReachabilitytips(append([]crypto.Hash{tips[i]}, bl.Tips...) ) { // avoid any tips which fail reachability test - continue - } - if len(bl.Tips) == 0 || (len(bl.Tips)>=1 && chain.Load_Height_for_BL_ID(bl.Tips[0]) >= chain.Load_Height_for_BL_ID(tips[i]) && chain.Load_Height_for_BL_ID(bl.Tips[0]) - chain.Load_Height_for_BL_ID(tips[i]) <= config.STABLE_LIMIT/2) { - bl.Tips = append(bl.Tips, tips[i]) - } + if !chain.verifyNonReachabilitytips(append([]crypto.Hash{tips[i]}, bl.Tips...)) { // avoid any tips which fail reachability test + continue + } + if len(bl.Tips) == 0 || (len(bl.Tips) >= 1 && chain.Load_Height_for_BL_ID(bl.Tips[0]) >= chain.Load_Height_for_BL_ID(tips[i]) && chain.Load_Height_for_BL_ID(bl.Tips[0])-chain.Load_Height_for_BL_ID(tips[i]) <= config.STABLE_LIMIT/2) { + bl.Tips = append(bl.Tips, tips[i]) + } } //fmt.Printf("miner block placing tips %+v\n", bl.Tips) @@ -274,7 +274,7 @@ func (chain *Blockchain) Create_new_block_template_mining(top_hash crypto.Hash, cache_block_mutex.Lock() defer cache_block_mutex.Unlock() - if (cache_block.Timestamp +1) < (uint64(uint64(time.Now().UTC().Unix()))) || (cache_block.Timestamp > 0 && int64(cache_block.Height) != chain.Get_Height()+1) { + if (cache_block.Timestamp+1) < (uint64(uint64(time.Now().UTC().Unix()))) || (cache_block.Timestamp > 0 && int64(cache_block.Height) != chain.Get_Height()+1) { _, bl = chain.Create_new_miner_block(miner_address, nil) cache_block = bl // setup cache for 1 sec } else { @@ -426,7 +426,7 @@ func (chain *Blockchain) Accept_new_block(block_template []byte, blockhashing_bl cache_block.Timestamp = 0 // expire cache block if !chain.simulator { // if not in simulator mode, relay block to the chain - chain.P2P_Block_Relayer(cbl, 0) // lets relay the block to network + chain.P2P_Block_Relayer(cbl, 0) // lets relay the block to network } } else { logger.Warnf("Block Rejected %s error %s", bl.GetHash(), err) diff --git a/blockchain/regpool/regpool.go b/blockchain/regpool/regpool.go index 7e4a02e..b9a2208 100644 --- a/blockchain/regpool/regpool.go +++ b/blockchain/regpool/regpool.go @@ -49,15 +49,15 @@ type TX_Sorting_struct struct { // we can always come back and rewrite it // NOTE: the pool is now persistant type Regpool struct { - txs sync.Map //map[crypto.Hash]*regpool_object - address_map sync.Map //map[crypto.Hash]bool // contains key images of all txs - sorted_by_fee []crypto.Hash // contains txids sorted by fees - sorted []TX_Sorting_struct // contains TX sorting information, so as new block can be forged easily - modified bool // used to monitor whethel mem pool contents have changed, - height uint64 // track blockchain height - - relayer chan crypto.Hash // used for immediate relay - P2P_TX_Relayer p2p_TX_Relayer // actual pointer, setup by the dero daemon during runtime + txs sync.Map //map[crypto.Hash]*regpool_object + address_map sync.Map //map[crypto.Hash]bool // contains key images of all txs + sorted_by_fee []crypto.Hash // contains txids sorted by fees + sorted []TX_Sorting_struct // contains TX sorting information, so as new block can be forged easily + modified bool // used to monitor whethel mem pool contents have changed, + height uint64 // track blockchain height + + relayer chan crypto.Hash // used for immediate relay + P2P_TX_Relayer p2p_TX_Relayer // actual pointer, setup by the dero daemon during runtime // global variable , but don't see it utilisation here except fot tx verification //chain *Blockchain @@ -138,7 +138,7 @@ func Init_Regpool(params map[string]interface{}) (*Regpool, error) { loggerpool.Infof("Regpool started") atomic.AddUint32(&globals.Subsystem_Active, 1) // increment subsystem - regpool.relayer = make(chan crypto.Hash, 1024*10) + regpool.relayer = make(chan crypto.Hash, 1024*10) regpool.Exit_Mutex = make(chan bool) // initialize maps @@ -166,7 +166,7 @@ func Init_Regpool(params map[string]interface{}) (*Regpool, error) { result := regpool.Regpool_Add_TX(objects[i].Tx, 0) if result { // setup time //regpool.txs[objects[i].Tx.GetHash()] = &objects[i] // setup time and other artifacts - regpool.txs.Store(objects[i].Tx.GetHash(),&objects[i] ) + regpool.txs.Store(objects[i].Tx.GetHash(), &objects[i]) } } } @@ -191,16 +191,15 @@ func (pool *Regpool) HouseKeeping(height uint64, Verifier func(*transaction.Tran var delete_list []crypto.Hash pool.txs.Range(func(k, value interface{}) bool { - txhash := k.(crypto.Hash) + txhash := k.(crypto.Hash) v := value.(*regpool_object) - if !Verifier(v.Tx) { // this tx user has already registered - delete_list = append(delete_list, txhash) - } + if !Verifier(v.Tx) { // this tx user has already registered + delete_list = append(delete_list, txhash) + } return true }) - for i := range delete_list { pool.Regpool_Delete_TX(delete_list[i]) } @@ -219,7 +218,6 @@ func (pool *Regpool) Shutdown() { // collect all txs in pool and serialize them and store them var objects []regpool_object - pool.txs.Range(func(k, value interface{}) bool { v := value.(*regpool_object) objects = append(objects, *v) @@ -274,17 +272,16 @@ func (pool *Regpool) Regpool_Add_TX(tx *transaction.Transaction, Height uint64) pool.Lock() defer pool.Unlock() - if !tx.IsRegistration(){ + if !tx.IsRegistration() { return false } var object regpool_object - - if pool.Regpool_Address_Present(tx.MinerAddress) { - // loggerpool.Infof("Rejecting TX, since address already has registration information") - return false - } + if pool.Regpool_Address_Present(tx.MinerAddress) { + // loggerpool.Infof("Rejecting TX, since address already has registration information") + return false + } tx_hash := crypto.Hash(tx.GetHash()) @@ -294,21 +291,17 @@ func (pool *Regpool) Regpool_Add_TX(tx *transaction.Transaction, Height uint64) return false } - if !tx.IsRegistrationValid(){ + if !tx.IsRegistrationValid() { return false } - - - - // add all the key images to check double spend attack within the pool -//TODO -// for i := 0; i < len(tx.Vin); i++ { -// pool.address_map.Store(tx.Vin[i].(transaction.Txin_to_key).K_image,true) // add element to map for next check -// } + //TODO + // for i := 0; i < len(tx.Vin); i++ { + // pool.address_map.Store(tx.Vin[i].(transaction.Txin_to_key).K_image,true) // add element to map for next check + // } - pool.address_map.Store(tx.MinerAddress,true) + pool.address_map.Store(tx.MinerAddress, true) // we are here means we can add it to pool object.Tx = tx @@ -316,9 +309,9 @@ func (pool *Regpool) Regpool_Add_TX(tx *transaction.Transaction, Height uint64) object.Added = uint64(time.Now().UTC().Unix()) object.Size = uint64(len(tx.Serialize())) - - pool.txs.Store(tx_hash,&object) - pool.relayer <- tx_hash + + pool.txs.Store(tx_hash, &object) + pool.relayer <- tx_hash pool.modified = true // pool has been modified //pool.sort_list() // sort and update pool list @@ -363,19 +356,17 @@ func (pool *Regpool) Regpool_Delete_TX(txid crypto.Hash) (tx *transaction.Transa return nil } - - // we reached here means, we have the tx remove it from our list, do maintainance cleapup and discard it object := objecti.(*regpool_object) - tx = object.Tx + tx = object.Tx pool.txs.Delete(txid) // remove all the key images -//TODO -// for i := 0; i < len(object.Tx.Vin); i++ { -// pool.address_map.Delete(object.Tx.Vin[i].(transaction.Txin_to_key).K_image) -// } - pool.address_map.Delete(tx.MinerAddress) + //TODO + // for i := 0; i < len(object.Tx.Vin); i++ { + // pool.address_map.Delete(object.Tx.Vin[i].(transaction.Txin_to_key).K_image) + // } + pool.address_map.Delete(tx.MinerAddress) //pool.sort_list() // sort and update pool list pool.modified = true // pool has been modified @@ -384,8 +375,8 @@ func (pool *Regpool) Regpool_Delete_TX(txid crypto.Hash) (tx *transaction.Transa // get specific tx from mem pool without removing it func (pool *Regpool) Regpool_Get_TX(txid crypto.Hash) (tx *transaction.Transaction) { -// pool.Lock() -// defer pool.Unlock() + // pool.Lock() + // defer pool.Unlock() var ok bool var objecti interface{} @@ -404,16 +395,16 @@ func (pool *Regpool) Regpool_Get_TX(txid crypto.Hash) (tx *transaction.Transacti // return list of all txs in pool func (pool *Regpool) Regpool_List_TX() []crypto.Hash { -// pool.Lock() -// defer pool.Unlock() + // pool.Lock() + // defer pool.Unlock() var list []crypto.Hash pool.txs.Range(func(k, value interface{}) bool { - txhash := k.(crypto.Hash) + txhash := k.(crypto.Hash) //v := value.(*regpool_object) //objects = append(objects, *v) - list = append(list,txhash) + list = append(list, txhash) return true }) @@ -426,8 +417,6 @@ func (pool *Regpool) Regpool_List_TX() []crypto.Hash { return list } - - // print current regpool txs // TODO add sorting func (pool *Regpool) Regpool_Print() { @@ -438,16 +427,15 @@ func (pool *Regpool) Regpool_Print() { var vlist []*regpool_object pool.txs.Range(func(k, value interface{}) bool { - txhash := k.(crypto.Hash) + txhash := k.(crypto.Hash) v := value.(*regpool_object) //objects = append(objects, *v) - klist = append(klist,txhash) - vlist = append(vlist,v) + klist = append(klist, txhash) + vlist = append(vlist, v) return true }) - fmt.Printf("Total TX in regpool = %d\n", len(klist)) fmt.Printf("%20s %14s %7s %7s %6s %32s\n", "Added", "Last Relayed", "Relayed", "Size", "Height", "TXID") @@ -464,24 +452,21 @@ func (pool *Regpool) Regpool_flush() { var list []crypto.Hash pool.txs.Range(func(k, value interface{}) bool { - txhash := k.(crypto.Hash) + txhash := k.(crypto.Hash) //v := value.(*regpool_object) //objects = append(objects, *v) - list = append(list,txhash) + list = append(list, txhash) return true }) fmt.Printf("Total TX in regpool = %d \n", len(list)) fmt.Printf("Flushing regpool \n") - for i := range list { pool.Regpool_Delete_TX(list[i]) } } - - type p2p_TX_Relayer func(*transaction.Transaction, uint64) int // function type, exported in p2p but cannot use due to cyclic dependency // this tx relayer keeps on relaying tx and cleaning regpool @@ -493,7 +478,7 @@ func (pool *Regpool) Relayer_and_Cleaner() { for { select { - case txid := <-pool.relayer: + case txid := <-pool.relayer: if objecti, ok := pool.txs.Load(txid); !ok { break } else { @@ -516,38 +501,35 @@ func (pool *Regpool) Relayer_and_Cleaner() { } pool.txs.Range(func(ktmp, value interface{}) bool { - k := ktmp.(crypto.Hash) - v := value.(*regpool_object) - + k := ktmp.(crypto.Hash) + v := value.(*regpool_object) + select { // exit fast of possible case <-pool.Exit_Mutex: return false default: } - - if v.Relayed < 10 || // relay it now - (v.Relayed >= 4 && v.Relayed <= 20 && (time.Now().Unix()-v.RelayedAt) > 5) || // relay it now - (time.Now().Unix()-v.RelayedAt) > 4 { - if pool.P2P_TX_Relayer != nil { + if v.Relayed < 10 || // relay it now + (v.Relayed >= 4 && v.Relayed <= 20 && (time.Now().Unix()-v.RelayedAt) > 5) || // relay it now + (time.Now().Unix()-v.RelayedAt) > 4 { + if pool.P2P_TX_Relayer != nil { - relayed_count := pool.P2P_TX_Relayer(v.Tx, 0) - //relayed_count := 0 - if relayed_count > 0 { - v.Relayed += relayed_count + relayed_count := pool.P2P_TX_Relayer(v.Tx, 0) + //relayed_count := 0 + if relayed_count > 0 { + v.Relayed += relayed_count - //loggerpool.Debugf("%d %d\n",time.Now().Unix(), v.RelayedAt) - rlog.Tracef(1,"Relayed %s to %d peers (%d %d)", k, relayed_count, v.Relayed, (time.Now().Unix() - v.RelayedAt)) - v.RelayedAt = time.Now().Unix() - //loggerpool.Debugf("%d %d",time.Now().Unix(), v.RelayedAt) - } + //loggerpool.Debugf("%d %d\n",time.Now().Unix(), v.RelayedAt) + rlog.Tracef(1, "Relayed %s to %d peers (%d %d)", k, relayed_count, v.Relayed, (time.Now().Unix() - v.RelayedAt)) + v.RelayedAt = time.Now().Unix() + //loggerpool.Debugf("%d %d",time.Now().Unix(), v.RelayedAt) } } - - - return true - }) + } + return true + }) // loggerpool.Warnf("send Pool lock released") //pool.Unlock() diff --git a/blockchain/regpool/regpool_test.go b/blockchain/regpool/regpool_test.go index 3b58afa..2ed650d 100644 --- a/blockchain/regpool/regpool_test.go +++ b/blockchain/regpool/regpool_test.go @@ -103,13 +103,13 @@ func Test_mempool_Full_block_72_2c4738d3856e8e3e8f9fc4818a9197d4911af3010e067ec5 } // pool must have 1 key_image - + key_image_count := 0 pool.key_images.Range(func(k, value interface{}) bool { key_image_count++ return true }) - + if key_image_count != 1 { t.Errorf("Pool doesnot have necessary key image") } diff --git a/blockchain/store.go b/blockchain/store.go index a8bb1bd..8e99875 100644 --- a/blockchain/store.go +++ b/blockchain/store.go @@ -149,7 +149,7 @@ func (chain *Blockchain) Load_BL_FROM_ID(hash [32]byte) (*block.Block, error) { if block_data, err := chain.Store.Block_tx_store.ReadBlock(hash); err == nil { if err = bl.Deserialize(block_data); err != nil { // we should deserialize the block here - logger.Warnf("fError deserialiing block, block id %x len(data) %d data %x err %s", hash[:], len(block_data), block_data,err) + logger.Warnf("fError deserialiing block, block id %x len(data) %d data %x err %s", hash[:], len(block_data), block_data, err) return nil, err } diff --git a/blockchain/storetopo.go b/blockchain/storetopo.go index 922a465..a52ba67 100644 --- a/blockchain/storetopo.go +++ b/blockchain/storetopo.go @@ -38,8 +38,8 @@ type storetopofs struct { topomapping *os.File } -func (s TopoRecord)String() string { - return fmt.Sprintf("blid %x state version %d height %d",s.BLOCK_ID[:],s.State_Version, s.Height) +func (s TopoRecord) String() string { + return fmt.Sprintf("blid %x state version %d height %d", s.BLOCK_ID[:], s.State_Version, s.Height) } func (s *storetopofs) Open(basedir string) (err error) { @@ -52,7 +52,15 @@ func (s *storetopofs) Count() int64 { if err != nil { panic(fmt.Sprintf("cannot stat topofile. err %s", err)) } - return int64(fstat.Size() / int64(TOPORECORD_SIZE)) + count := int64(fstat.Size() / int64(TOPORECORD_SIZE)) + for ; count >= 1; count-- { + if record, err := s.Read(count - 1); err == nil && !record.IsClean() { + break + } else if err != nil { + panic(fmt.Sprintf("cannot read topofile. err %s", err)) + } + } + return count } // it basically represents Load_Block_Topological_order_at_index @@ -167,7 +175,7 @@ func (s *storetopofs) binarySearchHeight(targetheight int64) (blids []crypto.Has startIndex := int64(0) - total_records := int64(s.Count() - 1) + total_records := int64(s.Count()) endIndex := total_records midIndex := total_records / 2 @@ -175,40 +183,7 @@ func (s *storetopofs) binarySearchHeight(targetheight int64) (blids []crypto.Has return } - if endIndex < 100 { // basic search all - for i := int64(0); i <= endIndex; i++ { - record, _ := s.Read(i) - if record.Height == targetheight { - blids = append(blids, record.BLOCK_ID) - topos = append(topos, i) - } - } - blids, topos = SliceUniqTopoRecord(blids, topos) // unique the record - return - } - - // fmt.Printf("endindex1 %d targetheight %d\n", endIndex, targetheight) - /* - // check if we can avoid binary, if it can be done using last records - record, _ := s.Read(endIndex) // reading last record - if targetheight + 100 > record.Height { - fmt.Printf("avoided binary search endindex1 %d targetheight %d last record %+v\n", endIndex, targetheight, record) - for i, count := midIndex, 0; i <= total_records && count < 100; i, count = i+1, count+1 { - record, _ := s.Read(i) - if record.Height == targetheight { - blids = append(blids, record.BLOCK_ID) - topos = append(topos, i) - } - } - return - } - */ - - //fmt.Printf("entering loop startIndex %d endindex %d midIndex %d targetheight %d\n", startIndex, endIndex, midIndex, targetheight) for startIndex <= endIndex { - - //fmt.Printf("startIndex %d endindex %d midIndex %d targetheight %d\n", startIndex, endIndex, midIndex, targetheight) - record, _ := s.Read(midIndex) if record.Height >= targetheight-((config.STABLE_LIMIT*4)/2) && record.Height <= targetheight+((config.STABLE_LIMIT*4)/2) { diff --git a/cmd/dero-wallet-cli/easymenu_post_open.go b/cmd/dero-wallet-cli/easymenu_post_open.go index a3164a4..82a5db0 100644 --- a/cmd/dero-wallet-cli/easymenu_post_open.go +++ b/cmd/dero-wallet-cli/easymenu_post_open.go @@ -132,14 +132,14 @@ func handle_easymenu_post_open_command(l *readline.Instance, line string) (proce reg_tx := wallet.GetRegistrationTX() - if ConfirmYesNoDefaultNo(l, "Confirm Registration (y/N)") { + // at this point we must send the registration transaction fmt.Fprintf(l.Stderr(), "Wallet address : "+color_green+"%s"+color_white+" is going to be registered.Pls wait till the account is registered.", wallet.GetAddress()) wallet.SendTransaction(reg_tx) - } + case "6": offline_tx = true diff --git a/cmd/dero-wallet-cli/easymenu_pre_open.go b/cmd/dero-wallet-cli/easymenu_pre_open.go index 888bdac..9e9807f 100644 --- a/cmd/dero-wallet-cli/easymenu_pre_open.go +++ b/cmd/dero-wallet-cli/easymenu_pre_open.go @@ -28,6 +28,7 @@ import "github.com/deroproject/derohe/crypto" import "github.com/deroproject/derohe/config" import "github.com/deroproject/derohe/globals" import "github.com/deroproject/derohe/walletapi" +import "github.com/deroproject/derohe/walletapi/rpcserver" // display menu before a wallet is opened func display_easymenu_pre_open_command(l *readline.Instance) { @@ -206,7 +207,7 @@ func handle_easymenu_pre_open_command(l *readline.Instance, line string) { } // sets online mode, starts RPC server etc -func common_processing(wallet *walletapi.Wallet) { +func common_processing(wallet *walletapi.Wallet_Disk) { if globals.Arguments["--offline"].(bool) == true { //offline_mode = true } else { @@ -227,13 +228,13 @@ func common_processing(wallet *walletapi.Wallet) { rpc_address = globals.Arguments["--rpc-bind"].(string) } globals.Logger.Infof("Starting RPC server at %s", rpc_address) - err := wallet.Start_RPC_Server(rpc_address) - if err != nil { + + if _, err := rpcserver.RPCServer_Start(wallet); err != nil { globals.Logger.Warnf("Error starting rpc server err %s", err) } } - time.Sleep(time.Second) + time.Sleep(time.Second) } diff --git a/cmd/dero-wallet-cli/main.go b/cmd/dero-wallet-cli/main.go index ffc17d0..b82e268 100644 --- a/cmd/dero-wallet-cli/main.go +++ b/cmd/dero-wallet-cli/main.go @@ -33,7 +33,6 @@ import "sync/atomic" //import "bufio" //import "bytes" //import "net/http" -//import "encoding/hex" import "github.com/romana/rlog" import "github.com/chzyer/readline" @@ -84,9 +83,9 @@ Usage: ` var menu_mode bool = true // default display menu mode //var account_valid bool = false // if an account has been opened, do not allow to create new account in this session -var offline_mode bool // whether we are in offline mode -var sync_in_progress int // whether sync is in progress with daemon -var wallet *walletapi.Wallet //= &walletapi.Account{} // all account data is available here +var offline_mode bool // whether we are in offline mode +var sync_in_progress int // whether sync is in progress with daemon +var wallet *walletapi.Wallet_Disk //= &walletapi.Account{} // all account data is available here //var address string var sync_time time.Time // used to suitable update prompt @@ -119,8 +118,8 @@ func main() { log.Fatalf("Error while parsing options err: %s\n", err) } - // init the lookup table one, anyone importing walletapi should init this first - walletapi.Balance_lookup_table = walletapi.Initialize_LookupTable(1, 1<<19) + // init the lookup table one, anyone importing walletapi should init this first, this will take around 1 sec on any recent system + walletapi.Initialize_LookupTable(1, 1<<20) // We need to initialize readline first, so it changes stderr to ansi processor on windows l, err := readline.NewEx(&readline.Config{ @@ -275,6 +274,7 @@ func main() { if wallet != nil { common_processing(wallet) } + go walletapi.Keep_Connectivity() // maintain connectivity //pipe_reader, pipe_writer = io.Pipe() // create pipes @@ -436,7 +436,7 @@ func update_prompt(l *readline.Instance) { } // create a new wallet from scratch from random numbers -func Create_New_Wallet(l *readline.Instance) (w *walletapi.Wallet, err error) { +func Create_New_Wallet(l *readline.Instance) (w *walletapi.Wallet_Disk, err error) { // ask user a file name to store the data diff --git a/cmd/dero-wallet-cli/prompt.go b/cmd/dero-wallet-cli/prompt.go index 46dda44..4ca97cb 100644 --- a/cmd/dero-wallet-cli/prompt.go +++ b/cmd/dero-wallet-cli/prompt.go @@ -544,7 +544,7 @@ func ConfirmYesNoDefaultNo(l *readline.Instance, prompt_temporary string) bool { // confirms whether user knows the current password for the wallet // this is triggerred while transferring amount, changing settings and so on -func ValidateCurrentPassword(l *readline.Instance, wallet *walletapi.Wallet) bool { +func ValidateCurrentPassword(l *readline.Instance, wallet *walletapi.Wallet_Disk) bool { prompt_mutex.Lock() defer prompt_mutex.Unlock() @@ -636,7 +636,7 @@ func ReadConfirmedPassword(l *readline.Instance, first_prompt string, second_pro // confirms user to press a key // this is triggerred while transferring amount, changing settings and so on -func PressAnyKey(l *readline.Instance, wallet *walletapi.Wallet) { +func PressAnyKey(l *readline.Instance, wallet *walletapi.Wallet_Disk) { prompt_mutex.Lock() defer prompt_mutex.Unlock() @@ -741,7 +741,7 @@ func usage(w io.Writer) { } // display seed to the user in his preferred language -func display_seed(l *readline.Instance, wallet *walletapi.Wallet) { +func display_seed(l *readline.Instance, wallet *walletapi.Wallet_Disk) { seed := wallet.GetSeed() fmt.Fprintf(l.Stderr(), color_green+"PLEASE NOTE: the following 25 words can be used to recover access to your wallet. Please write them down and store them somewhere safe and secure. Please do not store them in your email or on file storage services outside of your immediate control."+color_white+"\n") fmt.Fprintf(os.Stderr, color_red+"%s"+color_white+"\n", seed) @@ -751,7 +751,7 @@ func display_seed(l *readline.Instance, wallet *walletapi.Wallet) { // display spend key // viewable wallet do not have spend secret key // TODO wee need to give user a warning if we are printing secret -func display_spend_key(l *readline.Instance, wallet *walletapi.Wallet) { +func display_spend_key(l *readline.Instance, wallet *walletapi.Wallet_Disk) { keys := wallet.Get_Keys() fmt.Fprintf(os.Stderr, "secret key: "+color_red+"%s"+color_white+"\n", keys.Secret.Text(16)) @@ -760,7 +760,7 @@ func display_spend_key(l *readline.Instance, wallet *walletapi.Wallet) { } // start a rescan from block 0 -func rescan_bc(wallet *walletapi.Wallet) { +func rescan_bc(wallet *walletapi.Wallet_Disk) { if wallet.GetMode() { // trigger rescan we the wallet is online wallet.Clean() // clean existing data from wallet //wallet.Rescan_From_Height(0) @@ -768,14 +768,14 @@ func rescan_bc(wallet *walletapi.Wallet) { } -func is_registered(wallet *walletapi.Wallet) bool { +func is_registered(wallet *walletapi.Wallet_Disk) bool { if wallet.Get_Registration_TopoHeight() == -1 { return false } return true } -func valid_registration_or_display_error(l *readline.Instance, wallet *walletapi.Wallet) bool { +func valid_registration_or_display_error(l *readline.Instance, wallet *walletapi.Wallet_Disk) bool { if !is_registered(wallet) { globals.Logger.Warnf("Your account is not registered.Please register.") } @@ -783,7 +783,7 @@ func valid_registration_or_display_error(l *readline.Instance, wallet *walletapi } // show the transfers to the user originating from this account -func show_transfers(l *readline.Instance, wallet *walletapi.Wallet, limit uint64) { +func show_transfers(l *readline.Instance, wallet *walletapi.Wallet_Disk, limit uint64) { available := true in := true diff --git a/cmd/derod/main.go b/cmd/derod/main.go index 1f95501..387f169 100644 --- a/cmd/derod/main.go +++ b/cmd/derod/main.go @@ -22,7 +22,7 @@ import "time" import "fmt" import "bytes" -//import "bufio" +import "bufio" import "strings" import "strconv" import "runtime" @@ -531,7 +531,6 @@ func main() { if start > stop || stop > int64(chain.Load_TOPO_HEIGHT()) { log.Warnf("Stop value should be > start and current height\n") continue - } log.Infof("Printing block chain from %d to %d\n", start, stop) @@ -797,60 +796,59 @@ func main() { // can be used to debug/deserialize blocks // it can be used for blocks not in chain case command == "parse_block": - /* - if len(line_parts) != 2 { - globals.Logger.Warnf("parse_block needs a block in hex format") - continue - } - block_raw, err := hex.DecodeString(strings.ToLower(line_parts[1])) + if len(line_parts) != 2 { + globals.Logger.Warnf("parse_block needs a block in hex format") + continue + } + + block_raw, err := hex.DecodeString(strings.ToLower(line_parts[1])) + if err != nil { + fmt.Printf("err while hex decoding block err %s\n", err) + continue + } + + var bl block.Block + err = bl.Deserialize(block_raw) + if err != nil { + globals.Logger.Warnf("Error deserializing block err %s", err) + continue + } + + // decode and print block as much as possible + fmt.Printf("Block ID : %s\n", bl.GetHash()) + fmt.Printf("PoW: %s\n", bl.GetPoWHash()) // block height + fmt.Printf("Height: %d\n", bl.Height) + tips_found := true + for i := range bl.Tips { + _, err := chain.Load_BL_FROM_ID(bl.Tips[i]) if err != nil { - fmt.Printf("err while hex decoding block err %s\n", err) - continue + fmt.Printf("Tips %s not in our DB", bl.Tips[i]) + tips_found = false + break } + } + fmt.Printf("Tips: %d %+v\n", len(bl.Tips), bl.Tips) // block height + fmt.Printf("Txs: %d %+v\n", len(bl.Tx_hashes), bl.Tx_hashes) // block height + expected_difficulty := new(big.Int).SetUint64(0) + if tips_found { // we can solve diffculty + expected_difficulty = chain.Get_Difficulty_At_Tips(bl.Tips) + fmt.Printf("Difficulty: %s\n", expected_difficulty.String()) - var bl block.Block - err = bl.Deserialize(block_raw) - if err != nil { - globals.Logger.Warnf("Error deserializing block err %s", err) - continue - } + powsuccess := chain.VerifyPoW(&bl) + fmt.Printf("PoW verification %+v\n", powsuccess) - // decode and print block as much as possible - fmt.Printf("Block ID : %s\n", bl.GetHash()) - fmt.Printf("PoW: %s\n", bl.GetPoWHash()) // block height - fmt.Printf("Height: %d\n", bl.Miner_TX.Vin[0].(transaction.Txin_gen).Height) - tips_found := true - for i := range bl.Tips { - _, err := chain.Load_BL_FROM_ID(nil, bl.Tips[i]) - if err != nil { - fmt.Printf("Tips %s not in our DB", bl.Tips[i]) - tips_found = false + PoW := bl.GetPoWHash() + for i := expected_difficulty.Uint64(); i >= 1; i-- { + if blockchain.CheckPowHashBig(PoW, new(big.Int).SetUint64(i)) == true { + fmt.Printf("Block actually has max Difficulty: %d\n", i) break } } - fmt.Printf("Tips: %d %+v\n", len(bl.Tips), bl.Tips) // block height - fmt.Printf("Txs: %d %+v\n", len(bl.Tx_hashes), bl.Tx_hashes) // block height - expected_difficulty := new(big.Int).SetUint64(0) - if tips_found { // we can solve diffculty - expected_difficulty = chain.Get_Difficulty_At_Tips(nil, bl.Tips) - fmt.Printf("Difficulty: %s\n", expected_difficulty.String()) - powsuccess := chain.VerifyPoW(nil, &bl) - fmt.Printf("PoW verification %+v\n", powsuccess) + } else { // difficulty cann not solved - PoW := bl.GetPoWHash() - for i := expected_difficulty.Uint64(); i >= 1; i-- { - if blockchain.CheckPowHashBig(PoW, new(big.Int).SetUint64(i)) == true { - fmt.Printf("Block actually has max Difficulty: %d\n", i) - break - } - } - - } else { // difficulty cann not solved - - } - */ + } case command == "print_tx": /* @@ -904,11 +902,10 @@ func main() { // fmt.Printf("chain diff %d\n",chain.Get_Difficulty_At_Block(chain.Top_ID)) //fmt.Printf("chain nw rate %d\n", chain.Get_Network_HashRate()) - //inc, out := p2p.Peer_Direction_Count() + inc, out := p2p.Peer_Direction_Count() - inc, out := 0, 0 - - mempool_tx_count := 0 // len(chain.Mempool.Mempool_List_TX()) + mempool_tx_count := len(chain.Mempool.Mempool_List_TX()) + regpool_tx_count := len(chain.Regpool.Regpool_List_TX()) //supply := chain.Load_Already_Generated_Coins_for_Topo_Index(nil, chain.Load_TOPO_HEIGHT(nil)) @@ -917,7 +914,7 @@ func main() { if supply > (1000000 * 1000000000000) { supply -= (1000000 * 1000000000000) // remove premine } - fmt.Printf("Network %s Height %d NW Hashrate %0.03f MH/sec TH %s Peers %d inc, %d out MEMPOOL size %d Total Supply %s DERO \n", globals.Config.Name, chain.Get_Height(), float64(chain.Get_Network_HashRate())/1000000.0, chain.Get_Top_ID(), inc, out, mempool_tx_count, globals.FormatMoney(supply)) + fmt.Printf("Network %s Height %d NW Hashrate %0.03f MH/sec TH %s Peers %d inc, %d out MEMPOOL size %d REGPOOL %d Total Supply %s DERO \n", globals.Config.Name, chain.Get_Height(), float64(chain.Get_Network_HashRate())/1000000.0, chain.Get_Top_ID(), inc, out, mempool_tx_count, regpool_tx_count, globals.FormatMoney(supply)) // print hardfork status on second line hf_state, _, _, threshold, version, votes, window := chain.Get_HF_info() @@ -952,8 +949,39 @@ func main() { case strings.ToLower(line) == "quit": close(Exit_In_Progress) goto exit - case strings.ToLower(line) == "graph": - //blockchain.WriteBlockChainTree(chain, "/tmp/graph.dot") + case command == "graph": + start := int64(0) + stop := int64(0) + + if len(line_parts) != 3 { + log.Warnf("This function requires 2 parameters, start height and end height\n") + continue + } + if s, err := strconv.ParseInt(line_parts[1], 10, 64); err == nil { + start = s + } else { + log.Warnf("Invalid start value err %s", err) + continue + } + + if s, err := strconv.ParseInt(line_parts[2], 10, 64); err == nil { + stop = s + } else { + log.Warnf("Invalid stop value err %s", err) + continue + } + + if start < 0 || start > int64(chain.Load_TOPO_HEIGHT()) { + log.Warnf("Start value should be be between 0 and current height\n") + continue + } + if start > stop || stop > int64(chain.Load_TOPO_HEIGHT()) { + log.Warnf("Stop value should be > start and current height\n") + continue + } + + log.Infof("Writing block chain graph dot format from %d to %d to /tmp/graph.dot\n", start, stop) + WriteBlockChainTree(chain, "/tmp/graph.dot", start, stop) case command == "pop": @@ -1106,6 +1134,82 @@ exit: } } +func writenode(chain *blockchain.Blockchain, w *bufio.Writer, blid crypto.Hash, start_height int64) { // process a node, recursively + + w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) + + color := "white" + + if chain.Isblock_SideBlock(blid) { + color = "yellow" + } + if chain.IsBlockSyncBlockHeight(blid) { + color = "green" + } + + // now dump the interconnections + bl, err := chain.Load_BL_FROM_ID(blid) + + var acckey crypto.Point + if err := acckey.DecodeCompressed(bl.Miner_TX.MinerAddress[:]); err != nil { + panic(err) + } + + addr := address.NewAddressFromKeys(&acckey) + addr.Mainnet = globals.IsMainnet() + + w.WriteString(fmt.Sprintf("L%s [ fillcolor=%s label = \"%s %d height %d score %d stored %d order %d\nminer %s\" ];\n", blid.String(), color, blid.String(), 0, chain.Load_Height_for_BL_ID(blid), 0, chain.Load_Block_Cumulative_Difficulty(blid), chain.Load_Block_Topological_order(blid), addr.String())) + w.WriteString(fmt.Sprintf("}\n")) + + if err != nil { + fmt.Printf("err loading block %s err %s\n", blid, err) + return + } + if int64(bl.Height) > start_height { + for i := range bl.Tips { + w.WriteString(fmt.Sprintf("L%s -> L%s ;\n", bl.Tips[i].String(), blid.String())) + } + } + +} + +func WriteBlockChainTree(chain *blockchain.Blockchain, filename string, start_height, stop_height int64) (err error) { + + var node_map = map[crypto.Hash]bool{} + + for i := start_height; i < stop_height; i++ { + blids := chain.Get_Blocks_At_Height(i) + + for _, blid := range blids { + if _, ok := node_map[blid]; ok { + panic("duplicate block should not be there") + } else { + node_map[blid] = true + } + } + } + + f, err := os.Create(filename) + if err != nil { + return + } + defer f.Close() + + w := bufio.NewWriter(f) + defer w.Flush() + w.WriteString("digraph dero_blockchain_graph { \n") + + for blid := range node_map { + writenode(chain, w, blid, start_height) + } + //g := Generate_Genesis_Block() + //writenode(chain, dbtx, w, g.GetHash()) + + w.WriteString("}\n") + + return +} + func prettyprint_json(b []byte) []byte { var out bytes.Buffer err := json.Indent(&out, b, "", " ") @@ -1170,7 +1274,7 @@ var completer = readline.NewPrefixCompleter( readline.PcItem("sleep"), */ readline.PcItem("diff"), - readline.PcItem("dev_verify_pool"), + //readline.PcItem("dev_verify_pool"), //readline.PcItem("dev_verify_chain_doublespend"), readline.PcItem("mempool_flush"), readline.PcItem("mempool_delete_tx"), diff --git a/cmd/derod/rpc_dero_getblocktemplate.go b/cmd/derod/rpc_dero_getblocktemplate.go index ab16bfd..a58a027 100644 --- a/cmd/derod/rpc_dero_getblocktemplate.go +++ b/cmd/derod/rpc_dero_getblocktemplate.go @@ -44,16 +44,16 @@ func (DERO_RPC_APIS) GetBlockTemplate(ctx context.Context, p structures.GetBlock } }() /* - if !get_block_limiter.Allow() { // if rate limiter allows, then add block to chain - logger.Warnf("Too many get block template requests per sec rejected by chain.") + if !get_block_limiter.Allow() { // if rate limiter allows, then add block to chain + logger.Warnf("Too many get block template requests per sec rejected by chain.") - return nil,&jsonrpc.Error{ - Code: jsonrpc.ErrorCodeInvalidRequest, - Message: "Too many get block template requests per sec rejected by chain.", - } + return nil,&jsonrpc.Error{ + Code: jsonrpc.ErrorCodeInvalidRequest, + Message: "Too many get block template requests per sec rejected by chain.", + } - } + } */ // validate address diff --git a/cmd/derod/websocket_server.go b/cmd/derod/websocket_server.go index ccff410..84d0a5b 100644 --- a/cmd/derod/websocket_server.go +++ b/cmd/derod/websocket_server.go @@ -27,6 +27,8 @@ import "context" import "strings" import "runtime/debug" +import "github.com/romana/rlog" + import "github.com/deroproject/derohe/config" import "github.com/deroproject/derohe/globals" import "github.com/deroproject/derohe/blockchain" @@ -56,6 +58,39 @@ type RPCServer struct { var chain *blockchain.Blockchain var logger *log.Entry +var client_connections sync.Map + +var options = &jrpc2.ServerOptions{AllowPush: true} + +// this function triggers notification to all clients that they should repoll +func Notify_Block_Addition() { + + for { + chain.RPC_NotifyNewBlock.L.Lock() + chain.RPC_NotifyNewBlock.Wait() + chain.RPC_NotifyNewBlock.L.Unlock() + client_connections.Range(func(key, value interface{}) bool { + + key.(*jrpc2.Server).Notify(context.Background(), "Repoll", nil) + return true + }) + } +} + +func Notify_Height_Changes() { + + for { + chain.RPC_NotifyNewBlock.L.Lock() + chain.RPC_NotifyNewBlock.Wait() + chain.RPC_NotifyNewBlock.L.Unlock() + client_connections.Range(func(key, value interface{}) bool { + + key.(*jrpc2.Server).Notify(context.Background(), "HRepoll", nil) + return true + }) + } +} + func RPCServer_Start(params map[string]interface{}) (*RPCServer, error) { var err error @@ -222,6 +257,8 @@ func (r *RPCServer) Run() { //r.mux.HandleFunc("/json_rpc/debug", mr.ServeDebug) + go Notify_Block_Addition() // process all blocks + go Notify_Height_Changes() // gives notification of changed height if err := r.srv.ListenAndServe(); err != http.ErrServerClosed { logger.Warnf("ERR listening to address err %s", err) } @@ -232,10 +269,11 @@ func hello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "DERO BLOCKCHAIN Hello world!") } -var upgrader = websocket.Upgrader{} // use default options +var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} // use default options func ws_handler(w http.ResponseWriter, r *http.Request) { + var ws_server *jrpc2.Server defer func() { // safety so if anything wrong happens, verification fails @@ -243,17 +281,23 @@ func ws_handler(w http.ResponseWriter, r *http.Request) { logger.Warnf("Recovered while processing websocket request, Stack trace below ") logger.Warnf("Stack trace \n%s", debug.Stack()) } + if ws_server != nil { + client_connections.Delete(ws_server) + } }() c, err := upgrader.Upgrade(w, r, nil) if err != nil { - log.Print("upgrade:", err) + rlog.Warnf("upgrade:", err) return } + defer c.Close() input_output := rwc.New(c) - jrpc2.NewServer(assigner, nil).Start(channel.RawJSON(input_output, input_output)).Wait() + ws_server = jrpc2.NewServer(assigner, options).Start(channel.RawJSON(input_output, input_output)) + client_connections.Store(ws_server, 1) + ws_server.Wait() } diff --git a/cmd/explorer/templates.go b/cmd/explorer/templates.go index 9ca0a4a..f6442a3 100644 --- a/cmd/explorer/templates.go +++ b/cmd/explorer/templates.go @@ -512,7 +512,7 @@ var main_template string = `

Transactions in the last 11 blocks

(Median size of these blocks: 0.09 kB)

- + {{ template "paging" . }}
diff --git a/config/config.go b/config/config.go index 2239fc9..5c33e0c 100644 --- a/config/config.go +++ b/config/config.go @@ -26,7 +26,7 @@ import "github.com/deroproject/derohe/crypto" // later hardforks can make it lower by 1 sec, say every 6 months or so, until the system reaches 3 secs // by that time, networking,space requirements and processing requiremtn will probably outgrow homeusers // since most mining nodes will be running in datacenter, 3 secs blocks c -const BLOCK_TIME = uint64(30) +const BLOCK_TIME = uint64(18) // we are ignoring leap seconds from calculations @@ -113,7 +113,7 @@ var Mainnet = CHAIN_CONFIG{Name: "mainnet", } var Testnet = CHAIN_CONFIG{Name: "testnet", // testnet will always have last 3 bytes 0 - Network_ID: uuid.FromBytesOrNil([]byte{0x59, 0xd7, 0xf7, 0xe9, 0xdd, 0x48, 0xd5, 0xfd, 0x13, 0x0a, 0xf6, 0xe0, 0x23, 0x00, 0x00, 0x00}), + Network_ID: uuid.FromBytesOrNil([]byte{0x59, 0xd7, 0xf7, 0xe9, 0xdd, 0x48, 0xd5, 0xfd, 0x13, 0x0a, 0xf6, 0xe0, 0x24, 0x00, 0x00, 0x00}), P2P_Default_Port: 40401, RPC_Default_Port: 40402, Wallet_RPC_Default_Port: 40403, diff --git a/config/version.go b/config/version.go index 281eb96..4a112b4 100644 --- a/config/version.go +++ b/config/version.go @@ -20,4 +20,4 @@ import "github.com/blang/semver" // right now it has to be manually changed // do we need to include git commitsha?? -var Version = semver.MustParse("3.0.0-11.DEROHE.alpha+20122020") +var Version = semver.MustParse("3.0.0-22.DEROHE.alpha+27122020") diff --git a/crypto/bn256/curve.go b/crypto/bn256/curve.go index 68be3a3..d017915 100644 --- a/crypto/bn256/curve.go +++ b/crypto/bn256/curve.go @@ -207,13 +207,16 @@ func (c *curvePoint) Mul(a *curvePoint, scalar *big.Int) { } // Transforms Jacobian coordinates to Affine coordinates -// (X' : Y' : Z) -> (X'/(Z^2) : Y'/(Z^3) : 1) +// (X' : Y' : Z) -> (X'/(Z^2) : Y'/(Z^3) : 1) func (c *curvePoint) MakeAffine() { - if c.z == *newGFp(1) { + // point0 := *newGFp(0) + // point1 := *newGFp(1) + + if c.z == point1 { return - } else if c.z == *newGFp(0) { // return point at infinity if z = 0 + } else if c.z == point0 { // return point at infinity if z = 0 c.x = gfP{0} - c.y = *newGFp(1) + c.y = point1 c.t = gfP{0} return } @@ -222,14 +225,14 @@ func (c *curvePoint) MakeAffine() { zInv.Invert(&c.z) t, zInv2 := &gfP{}, &gfP{} - gfpMul(t, &c.y, zInv) // t = y/z + gfpMul(t, &c.y, zInv) // t = y/z gfpMul(zInv2, zInv, zInv) // zInv2 = 1/(z^2) gfpMul(&c.x, &c.x, zInv2) // x = x/(z^2) - gfpMul(&c.y, t, zInv2) // y = y/(z^3) + gfpMul(&c.y, t, zInv2) // y = y/(z^3) - c.z = *newGFp(1) - c.t = *newGFp(1) + c.z = point1 + c.t = point1 } func (c *curvePoint) Neg(a *curvePoint) { @@ -238,3 +241,78 @@ func (c *curvePoint) Neg(a *curvePoint) { c.z.Set(&a.z) c.t = gfP{0} } + +var point0 = *newGFp(0) +var point1 = *newGFp(1) + +// this will do batch inversions and thus optimize lookup table generation +// Montgomery Batch Inversion based trick +type G1Array []*G1 + +func (points G1Array) MakeAffine() { + // point0 := *newGFp(0) + // point1 := *newGFp(1) + + accum := newGFp(1) + + var scratch_backup [256]gfP + + var scratch []gfP + if len(points) <= 256 { + scratch = scratch_backup[:0] // avoid allocation is possible + } + for _, e := range points { + if e.p == nil { + e.p = &curvePoint{} + } + scratch = append(scratch, *accum) + if e.p.z == point1 { + continue + } else if e.p.z == point0 { // return point at infinity if z = 0 + e.p.x = gfP{0} + e.p.y = point1 + e.p.t = gfP{0} + continue + } + + gfpMul(accum, accum, &e.p.z) // accum *= z + + /* + zInv := &gfP{} + zInv.Invert(&e.p.z) + fmt.Printf("%d inv %s\n",i, zInv) + */ + } + + zInv_accum := gfP{} + zInv_accum.Invert(accum) + + tmp := gfP{} + zInv := &gfP{} + + for i := len(points) - 1; i >= 0; i-- { + e := points[i] + + if e.p.z == point1 { + continue + } else if e.p.z == point0 { // return point at infinity if z = 0 + continue + } + + tmp = gfP{} + gfpMul(&tmp, &zInv_accum, &e.p.z) + gfpMul(zInv, &zInv_accum, &scratch[i]) + zInv_accum = tmp + // fmt.Printf("%d inv %s\n",i, zInv) + + t, zInv2 := &gfP{}, &gfP{} + gfpMul(t, &e.p.y, zInv) // t = y/z + gfpMul(zInv2, zInv, zInv) // zInv2 = 1/(z^2) + + gfpMul(&e.p.x, &e.p.x, zInv2) // x = x/(z^2) + gfpMul(&e.p.y, t, zInv2) // y = y/(z^3) + + e.p.z = point1 + e.p.t = point1 + } +} diff --git a/crypto/bn256/curve_test.go b/crypto/bn256/curve_test.go new file mode 100644 index 0000000..3f4f884 --- /dev/null +++ b/crypto/bn256/curve_test.go @@ -0,0 +1,66 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package bn256 + +import ( + "crypto/rand" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestG1Array(t *testing.T) { + count := 8 + + var g1array G1Array + var g1array_opt G1Array + + for i := 0; i < count; i++ { + a, _ := rand.Int(rand.Reader, Order) + g1array = append(g1array, new(G1).ScalarBaseMult(a)) + g1array_opt = append(g1array_opt, new(G1).ScalarBaseMult(a)) + } + g1array_opt.MakeAffine() + for i := range g1array_opt { + require.Equal(t, g1array_opt[i].p.z, *newGFp(1)) // current we are not testing points of infinity + } +} + +func benchmarksingleinverts(count int, b *testing.B) { + var g1array, g1backup G1Array + + for i := 0; i < count; i++ { + a, _ := rand.Int(rand.Reader, Order) + g1backup = append(g1backup, new(G1).ScalarBaseMult(a)) + } + + for n := 0; n < b.N; n++ { + g1array = g1array[:0] + for i := range g1backup { + g1array = append(g1array, new(G1).Set(g1backup[i])) + g1array[i].p.MakeAffine() + } + } +} + +func benchmarkbatchedinverts(count int, b *testing.B) { + var g1array, g1backup G1Array + + for i := 0; i < count; i++ { + a, _ := rand.Int(rand.Reader, Order) + g1backup = append(g1backup, new(G1).ScalarBaseMult(a)) + } + + for n := 0; n < b.N; n++ { + g1array = g1array[:0] + for i := range g1backup { + g1array = append(g1array, new(G1).Set(g1backup[i])) + } + g1array.MakeAffine() + } +} + +func BenchmarkInverts_Single_256(b *testing.B) { benchmarksingleinverts(256, b) } +func BenchmarkInverts_Batched_256(b *testing.B) { benchmarkbatchedinverts(256, b) } diff --git a/crypto/bn256/g1_serialization.go b/crypto/bn256/g1_serialization.go index 1590c97..c508984 100644 --- a/crypto/bn256/g1_serialization.go +++ b/crypto/bn256/g1_serialization.go @@ -52,13 +52,14 @@ func (e *G1) IsHigherY() bool { e.p = &curvePoint{} } - yCoord := &gfP{} - yCoord.Set(&e.p.y) + var yCoord gfP + //yCoord.Set(&e.p.y) + yCoord = e.p.y - yCoordNeg := &gfP{} - gfpNeg(yCoordNeg, yCoord) + var yCoordNeg gfP + gfpNeg(&yCoordNeg, &yCoord) - res := gfpCmp(yCoord, yCoordNeg) + res := gfpCmp(&yCoord, &yCoordNeg) if res == 1 { // yCoord > yCoordNeg return true } else if res == -1 { @@ -104,6 +105,39 @@ func (e *G1) EncodeCompressed() []byte { return ret } +// returns to buffer rather than allocation from GC +func (e *G1) EncodeCompressedToBuf(ret []byte) { + // Check nil pointers + if e.p == nil { + e.p = &curvePoint{} + } + + e.p.MakeAffine() + //ret := make([]byte, G1CompressedSize) + + // Flag the encoding with the compressed flag + ret[0] |= serializationCompressed + + if e.p.IsInfinity() { + // Flag the encoding with the infinity flag + ret[0] |= serializationInfinity + return + } + + if e.IsHigherY() { + // Flag the encoding with the bigY flag + ret[0] |= serializationBigY + } + + // We start the serializagtion of the coordinates at the index 1 + // Since the index 0 in the `ret` corresponds to the masking + temp := &gfP{} + montDecode(temp, &e.p.x) + temp.Marshal(ret[1:]) + + return +} + // EncodeUncompressed converts the compressed point e into bytes // Take a point P in Jacobian form (where each coordinate is MontEncoded) // and encodes it by going back to affine coordinates and montDecode all coordinates @@ -220,8 +254,8 @@ func (e *G1) DecodeCompressed(encoding []byte) error { // Unmarshal the points and check their caps if e.p == nil { e.p = &curvePoint{} - } - { + } + { e.p.x, e.p.y = gfP{0}, gfP{0} e.p.z, e.p.t = *newGFp(1), *newGFp(1) } @@ -232,8 +266,6 @@ func (e *G1) DecodeCompressed(encoding []byte) error { copy(bin, encoding) bin[0] &= serializationMask - - // Decode the point at infinity in the compressed form if encoding[0]&serializationInfinity != 0 { if encoding[0]&serializationBigY != 0 { @@ -248,11 +280,10 @@ func (e *G1) DecodeCompressed(encoding []byte) error { } } e.p.SetInfinity() - //panic("point is infinity") + //panic("point is infinity") return nil } - // Decompress the point P (P =/= ∞) var err error if err = e.p.x.Unmarshal(bin[1:]); err != nil { @@ -267,7 +298,6 @@ func (e *G1) DecodeCompressed(encoding []byte) error { return err } e.p.y = *y - // The flag serializationBigY is set (so the point pt with the higher Y is encoded) // but the point e retrieved from the `getYFromX` is NOT the higher, then we inverse @@ -281,7 +311,6 @@ func (e *G1) DecodeCompressed(encoding []byte) error { } } - // No need to check that the point e.p is on the curve // since we retrieved y from x by using the curve equation. // Adding it would be redundant diff --git a/crypto/bn256/gfp_decl.go b/crypto/bn256/gfp_decl.go index b5f505b..fdea5c1 100644 --- a/crypto/bn256/gfp_decl.go +++ b/crypto/bn256/gfp_decl.go @@ -22,4 +22,4 @@ func gfpAdd(c, a, b *gfP) func gfpSub(c, a, b *gfP) //go:noescape -func gfpMul(c, a, b *gfP) \ No newline at end of file +func gfpMul(c, a, b *gfP) diff --git a/crypto/paymentid.go b/crypto/paymentid.go index 274f6b6..519e3e5 100644 --- a/crypto/paymentid.go +++ b/crypto/paymentid.go @@ -21,7 +21,7 @@ import "github.com/deroproject/derohe/crypto/bn256" // BUG BUG BUG this needs to be updated and add more context // this function is used to encrypt/decrypt payment id // as the operation is symmetric XOR, is the same in both direction -// +// func EncryptDecryptPaymentID(blinder *bn256.G1, input []byte) (output []byte) { // input must be exactly 8 bytes long diff --git a/crypto/sha3/doc.go b/crypto/sha3/doc.go index 11508f7..c06a330 100644 --- a/crypto/sha3/doc.go +++ b/crypto/sha3/doc.go @@ -63,4 +63,4 @@ // They produce output of the same length, with the same security strengths // against all attacks. This means, in particular, that SHA3-256 only has // 128-bit collision resistance, because its output length is 32 bytes. -package sha3 +package sha3 diff --git a/glue/rwc/rwc.go b/glue/rwc/rwc.go index 43df1c3..0989fc7 100644 --- a/glue/rwc/rwc.go +++ b/glue/rwc/rwc.go @@ -1,9 +1,10 @@ +// +build !wasm + package rwc import ( - "io" - "github.com/gorilla/websocket" + "io" ) type ReadWriteCloser struct { diff --git a/glue/rwc/rwc_nhyoor.go b/glue/rwc/rwc_nhyoor.go new file mode 100644 index 0000000..1bc6955 --- /dev/null +++ b/glue/rwc/rwc_nhyoor.go @@ -0,0 +1,68 @@ +package rwc + +import ( + "context" + "io" + "nhooyr.io/websocket" +) + +type ReadWriteCloserNhooyr struct { + WS *websocket.Conn + r io.Reader + w io.WriteCloser +} + +func NewNhooyr(conn *websocket.Conn) *ReadWriteCloserNhooyr { + return &ReadWriteCloserNhooyr{WS: conn} +} + +func (rwc *ReadWriteCloserNhooyr) Read(p []byte) (n int, err error) { + if rwc.r == nil { + rwc.WS.SetReadLimit(2 * 1024 * 1024) + _, rwc.r, err = rwc.WS.Reader(context.Background()) + if err != nil { + return 0, err + } + } + for n = 0; n < len(p); { + var m int + m, err = rwc.r.Read(p[n:]) + n += m + if err == io.EOF { + rwc.r = nil + } + if err != nil { + break + } + } + return +} + +func (rwc *ReadWriteCloserNhooyr) Write(p []byte) (n int, err error) { + if rwc.w == nil { + rwc.w, err = rwc.WS.Writer(context.Background(), websocket.MessageText) + if err != nil { + return 0, err + } + } + for n = 0; n < len(p); { + var m int + m, err = rwc.w.Write(p) + n += m + if err != nil { + break + } + } + if err != nil || n == len(p) { + err = rwc.Close() + } + return +} + +func (rwc *ReadWriteCloserNhooyr) Close() (err error) { + if rwc.w != nil { + err = rwc.w.Close() + rwc.w = nil + } + return err +} diff --git a/p2p/connection_handler.go b/p2p/connection_handler.go index 093c7e6..1dba0aa 100644 --- a/p2p/connection_handler.go +++ b/p2p/connection_handler.go @@ -38,10 +38,10 @@ import "github.com/vmihailenco/msgpack" import "github.com/deroproject/derohe/config" -//import "github.com/deroproject/derosuite/crypto" +import "github.com/deroproject/derohe/crypto" import "github.com/deroproject/derohe/globals" -//import "github.com/deroproject/derosuite/blockchain" +import "github.com/deroproject/derohe/blockchain" // This file defines what all needs to be responded to become a server ( handling incoming requests) @@ -58,24 +58,40 @@ func fill_common(common *Common_Struct) { } else { common.Cumulative_Difficulty = chain.Load_Block_Cumulative_Difficulty(high_block).String() } + + if toporecord, err := chain.Store.Topo_store.Read(common.TopoHeight); err == nil { + if ss, err := chain.Store.Balance_store.LoadSnapshot(uint64(toporecord.State_Version)); err == nil { + if balance_tree, err := ss.GetTree(blockchain.BALANCE_TREE); err == nil { + if bhash, err := balance_tree.Hash(); err == nil { + common.StateHash = bhash + } + } + } + } + common.Top_Version = uint64(chain.Get_Current_Version_at_Height(int64(common.Height))) // this must be taken from the hardfork } // used while sendint TX ASAP +// this also skips statehash func fill_common_skip_topoheight(common *Common_Struct) { - common.Height = chain.Get_Height() - //common.StableHeight = chain.Get_Stable_Height() - common.TopoHeight = chain.Load_TOPO_HEIGHT() - //common.Top_ID, _ = chain.Load_BL_ID_at_Height(common.Height - 1) + fill_common(common) + return + /* + common.Height = chain.Get_Height() + //common.StableHeight = chain.Get_Stable_Height() + common.TopoHeight = chain.Load_TOPO_HEIGHT() + //common.Top_ID, _ = chain.Load_BL_ID_at_Height(common.Height - 1) - high_block, err := chain.Load_Block_Topological_order_at_index(common.TopoHeight) - if err != nil { - common.Cumulative_Difficulty = "0" - } else { - common.Cumulative_Difficulty = chain.Load_Block_Cumulative_Difficulty(high_block).String() - } - common.Top_Version = uint64(chain.Get_Current_Version_at_Height(int64(common.Height))) // this must be taken from the hardfork + high_block, err := chain.Load_Block_Topological_order_at_index(common.TopoHeight) + if err != nil { + common.Cumulative_Difficulty = "0" + } else { + common.Cumulative_Difficulty = chain.Load_Block_Cumulative_Difficulty(high_block).String() + } + common.Top_Version = uint64(chain.Get_Current_Version_at_Height(int64(common.Height))) // this must be taken from the hardfork + */ } @@ -83,6 +99,7 @@ func fill_common_skip_topoheight(common *Common_Struct) { func (connection *Connection) Update(common *Common_Struct) { //connection.Lock() //defer connection.Unlock() + var hash crypto.Hash atomic.StoreInt64(&connection.Height, common.Height) // satify race detector GOD if common.StableHeight != 0 { atomic.StoreInt64(&connection.StableHeight, common.StableHeight) // satify race detector GOD @@ -105,6 +122,10 @@ func (connection *Connection) Update(common *Common_Struct) { if connection.Top_Version != common.Top_Version { atomic.StoreUint64(&connection.Top_Version, common.Top_Version) // satify race detector GOD } + if common.StateHash != hash { + connection.StateHash = common.StateHash + } + } // sets timeout based on connection state, so as stale connections are cleared quickly @@ -397,7 +418,6 @@ func Handle_Connection(conn net.Conn, remote_addr *net.TCPAddr, incoming bool, s case V2_COMMAND_HANDSHAKE: connection.Update(&command.Common) connection.Handle_Handshake(data_read) - case V2_COMMAND_SYNC: connection.Update(&command.Common) connection.Handle_TimedSync(data_read) @@ -405,7 +425,6 @@ func Handle_Connection(conn net.Conn, remote_addr *net.TCPAddr, incoming bool, s connection.Update(&command.Common) connection.Handle_ChainRequest(data_read) case V2_COMMAND_CHAIN_RESPONSE: - connection.Update(&command.Common) connection.Handle_ChainResponse(data_read) case V2_COMMAND_OBJECTS_REQUEST: @@ -417,10 +436,12 @@ func Handle_Connection(conn net.Conn, remote_addr *net.TCPAddr, incoming bool, s case V2_NOTIFY_NEW_BLOCK: // for notification, instead of syncing, we will process notificaton first connection.Handle_Notification_Block(data_read) connection.Update(&command.Common) // we do it a bit later so we donot staart syncing - case V2_NOTIFY_NEW_TX: connection.Update(&command.Common) connection.Handle_Notification_Transaction(data_read) + case V2_NOTIFY_INVENTORY: + connection.Update(&command.Common) + connection.Handle_Incoming_Inventory(data_read) default: connection.logger.Debugf("Unhandled v2 command %d", command.Command) diff --git a/p2p/connection_pool.go b/p2p/connection_pool.go index 6f7819c..39e3a4c 100644 --- a/p2p/connection_pool.go +++ b/p2p/connection_pool.go @@ -66,9 +66,11 @@ type Queued_Command struct { // golang restricts 64 bit uint64/int atomic on a 64 bit boundary // therefore all atomics are on the top type Connection struct { - Height int64 // last height sent by peer ( first member alignments issues) - StableHeight int64 // last stable height - TopoHeight int64 // topo height, current topo height, this is the only thing we require for syncing + Height int64 // last height sent by peer ( first member alignments issues) + StableHeight int64 // last stable height + TopoHeight int64 // topo height, current topo height, this is the only thing we require for syncing + StateHash crypto.Hash // statehash at the top + Pruned int64 // till where chain has been pruned on this node LastObjectRequestTime int64 // when was the last item placed in object list BytesIn uint64 // total bytes in @@ -260,9 +262,9 @@ func Connection_Print() { fmt.Printf("Connection info for peers\n") if globals.Arguments["--debug"].(bool) == true { - fmt.Printf("%-20s %-16s %-5s %-7s %-7s %23s %3s %5s %s %s %s %s %10s\n", "Remote Addr", "PEER ID", "PORT", " State", "Latency", "S/H/T", "DIR", "QUEUE", " IN", " OUT", " IN SPEED", " OUT SPEED", "Version") + fmt.Printf("%-20s %-16s %-5s %-7s %-7s %23s %3s %5s %s %s %s %s %16s %16s\n", "Remote Addr", "PEER ID", "PORT", " State", "Latency", "S/H/T", "DIR", "QUEUE", " IN", " OUT", " IN SPEED", " OUT SPEED", "Version", "Statehash") } else { - fmt.Printf("%-20s %-16s %-5s %-7s %-7s %17s %3s %5s %s %s %s %s %10s\n", "Remote Addr", "PEER ID", "PORT", " State", "Latency", "H/T", "DIR", "QUEUE", " IN", " OUT", " IN SPEED", " OUT SPEED", "Version") + fmt.Printf("%-20s %-16s %-5s %-7s %-7s %17s %3s %5s %s %s %s %s %16s %16s\n", "Remote Addr", "PEER ID", "PORT", " State", "Latency", "H/T", "DIR", "QUEUE", " IN", " OUT", " IN SPEED", " OUT SPEED", "Version", "Statehash") } @@ -320,11 +322,11 @@ func Connection_Print() { if globals.Arguments["--debug"].(bool) == true { hstring := fmt.Sprintf("%d/%d/%d", clist[i].StableHeight, clist[i].Height, clist[i].TopoHeight) - fmt.Printf("%-20s %16x %5d %7s %7s %23s %s %5d %7s %7s %8s %9s %10s %s\n", clist[i].Addr.IP, clist[i].Peer_ID, clist[i].Port, state, time.Duration(atomic.LoadInt64(&clist[i].Latency)).Round(time.Millisecond).String(), hstring, dir, clist[i].IsConnectionSyncing(), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesIn)), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesOut)), humanize.Bytes(uint64(clist[i].SpeedIn.Rate()/60)), humanize.Bytes(uint64(clist[i].SpeedOut.Rate()/60)), version, tag) + fmt.Printf("%-20s %16x %5d %7s %7s %23s %s %5d %7s %7s %8s %9s %16s %s %x\n", clist[i].Addr.IP, clist[i].Peer_ID, clist[i].Port, state, time.Duration(atomic.LoadInt64(&clist[i].Latency)).Round(time.Millisecond).String(), hstring, dir, clist[i].IsConnectionSyncing(), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesIn)), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesOut)), humanize.Bytes(uint64(clist[i].SpeedIn.Rate()/60)), humanize.Bytes(uint64(clist[i].SpeedOut.Rate()/60)), version, tag, clist[i].StateHash[:]) } else { hstring := fmt.Sprintf("%d/%d", clist[i].Height, clist[i].TopoHeight) - fmt.Printf("%-20s %16x %5d %7s %7s %17s %s %5d %7s %7s %8s %9s %10s %s\n", clist[i].Addr.IP, clist[i].Peer_ID, clist[i].Port, state, time.Duration(atomic.LoadInt64(&clist[i].Latency)).Round(time.Millisecond).String(), hstring, dir, clist[i].IsConnectionSyncing(), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesIn)), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesOut)), humanize.Bytes(uint64(clist[i].SpeedIn.Rate()/60)), humanize.Bytes(uint64(clist[i].SpeedOut.Rate()/60)), version, tag) + fmt.Printf("%-20s %16x %5d %7s %7s %17s %s %5d %7s %7s %8s %9s %16s %s %x\n", clist[i].Addr.IP, clist[i].Peer_ID, clist[i].Port, state, time.Duration(atomic.LoadInt64(&clist[i].Latency)).Round(time.Millisecond).String(), hstring, dir, clist[i].IsConnectionSyncing(), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesIn)), humanize.Bytes(atomic.LoadUint64(&clist[i].BytesOut)), humanize.Bytes(uint64(clist[i].SpeedIn.Rate()/60)), humanize.Bytes(uint64(clist[i].SpeedOut.Rate()/60)), version, tag, clist[i].StateHash[:8]) } @@ -542,18 +544,19 @@ func Broadcast_Tx(tx *transaction.Transaction, PeerID uint64) (relayed_count int } }() - var request Notify_New_Objects_Struct - + var request Object_Request_Struct fill_common_skip_topoheight(&request.Common) // fill common info, but skip topo height - request.Command = V2_NOTIFY_NEW_TX - request.Tx = tx.Serialize() + request.Command = V2_NOTIFY_INVENTORY + + txhash := tx.GetHash() + + request.Tx_list = append(request.Tx_list, txhash) serialized, err := msgpack.Marshal(&request) if err != nil { panic(err) } - txhash := tx.GetHash() our_height := chain.Get_Height() unique_map := UniqueConnections() @@ -585,16 +588,23 @@ func Broadcast_Tx(tx *transaction.Transaction, PeerID uint64) (relayed_count int } }() - connection.Send_Message(serialized) // send the bytes - - // mark the TX as having sent to this node - // when this tx is - connection.TXpool_cache_lock.Lock() + resend := true // disable cache if not possible due to options + // assuming the peer is good, he would like to obtain the tx ASAP if globals.Arguments["--lowcpuram"].(bool) == false && connection.TXpool_cache != nil { - connection.TXpool_cache[binary.LittleEndian.Uint64(txhash[:])] = uint32(time.Now().Unix()) + connection.TXpool_cache_lock.Lock() + if _, ok := connection.TXpool_cache[binary.LittleEndian.Uint64(txhash[:])]; !ok { + connection.TXpool_cache[binary.LittleEndian.Uint64(txhash[:])] = uint32(time.Now().Unix()) + resend = true + } else { + resend = false + } + connection.TXpool_cache_lock.Unlock() + } + + if resend { + connection.Send_Message(serialized) // send the bytes } - connection.TXpool_cache_lock.Unlock() }(v) } @@ -662,7 +672,7 @@ func trigger_sync() { //connection.Lock() recursive mutex are not suported // only choose highest available peers for syncing - if atomic.LoadUint32(&connection.State) != HANDSHAKE_PENDING && topoheight <= atomic.LoadInt64(&connection.TopoHeight) { // skip pre-handshake connections + if atomic.LoadUint32(&connection.State) != HANDSHAKE_PENDING && topoheight <= atomic.LoadInt64(&connection.TopoHeight) && topoheight >= connection.Pruned { // skip pre-handshake connections // check whether we are lagging with this connection //connection.Lock() islagging := chain.IsLagging(connection.CDIFF.Load().(*big.Int)) // we only use cdiff to see if we need to resync diff --git a/p2p/handshake.go b/p2p/handshake.go index 594d835..7a3c8a4 100644 --- a/p2p/handshake.go +++ b/p2p/handshake.go @@ -53,6 +53,7 @@ func (connection *Connection) Send_Handshake(request bool) { handshake.UTC_Time = int64(time.Now().UTC().Unix()) // send our UTC time handshake.Local_Port = uint32(P2P_Port) // export requested or default port handshake.Peer_ID = GetPeerID() // give our randomly generated peer id + handshake.Pruned = chain.LocatePruneTopo() if globals.Arguments["--lowcpuram"].(bool) == false { handshake.Flags = append(handshake.Flags, FLAG_LOWCPURAM) // add low cpu ram flag } @@ -126,6 +127,9 @@ func (connection *Connection) Handle_Handshake(buf []byte) { if len(handshake.Tag) < 128 { connection.Tag = handshake.Tag } + if handshake.Pruned >= 0 { + connection.Pruned = handshake.Pruned + } // TODO we must also add the peer to our list // which can be distributed to other peers @@ -181,7 +185,7 @@ func (connection *Connection) Handle_Handshake(buf []byte) { rlog.Debugf("Peer provides %d peers", len(handshake.PeerList)) for i := range handshake.PeerList { if i < 13 { - Peer_Add(&Peer{Address: handshake.PeerList[i].Addr , LastConnected : uint64(time.Now().UTC().Unix())}) + Peer_Add(&Peer{Address: handshake.PeerList[i].Addr, LastConnected: uint64(time.Now().UTC().Unix())}) } } diff --git a/p2p/inventory_handler.go b/p2p/inventory_handler.go new file mode 100644 index 0000000..f17b2c0 --- /dev/null +++ b/p2p/inventory_handler.go @@ -0,0 +1,135 @@ +// Copyright 2017-2021 DERO Project. All rights reserved. +// Use of this source code in any form is governed by RESEARCH license. +// license can be found in the LICENSE file. +// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 +// +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package p2p + +//import "fmt" +//import "net" +import "sync/atomic" +import "time" + +//import "container/list" + +import "github.com/romana/rlog" +import "github.com/vmihailenco/msgpack" + +//import "github.com/deroproject/derosuite/crypto" +//import "github.com/deroproject/derosuite/globals" + +import "github.com/deroproject/derohe/crypto" + +//import "github.com/deroproject/derosuite/globals" + +//import "github.com/deroproject/derosuite/blockchain" + +// we are sending object request +// right now we only send block ids +func (connection *Connection) Send_Inventory(blids []crypto.Hash, txids []crypto.Hash) { + + var request Object_Request_Struct + fill_common(&request.Common) // fill common info + request.Command = V2_NOTIFY_INVENTORY + + for i := range blids { + request.Block_list = append(request.Block_list, blids[i]) + } + + for i := range txids { + request.Tx_list = append(request.Tx_list, txids[i]) + } + + if len(blids) > 0 || len(txids) > 0 { + serialized, err := msgpack.Marshal(&request) // serialize and send + if err != nil { + panic(err) + } + + // use first object + + command := Queued_Command{Command: V2_COMMAND_OBJECTS_RESPONSE, BLID: blids, TXID: txids} + + connection.Objects <- command + atomic.StoreInt64(&connection.LastObjectRequestTime, time.Now().Unix()) + + // we should add to queue that we are waiting for object response + //command := Queued_Command{Command: V2_COMMAND_OBJECTS_RESPONSE, BLID: blids, TXID: txids, Started: time.Now()} + + connection.Lock() + //connection.Command_queue.PushBack(command) // queue command + connection.Send_Message_prelocked(serialized) + connection.Unlock() + rlog.Tracef(3, "object request sent contains %d blids %d txids %s ", len(blids), connection.logid) + } +} + +// peer has given his list of inventory +// if certain object is not in our list we request with the inventory +// if everything is already in our inventory, do nothing ignore +func (connection *Connection) Handle_Incoming_Inventory(buf []byte) { + var request Object_Request_Struct + var response Object_Request_Struct + + var blids, txids []crypto.Hash + + var dirty = false + + err := msgpack.Unmarshal(buf, &request) + if err != nil { + rlog.Warnf("Error while decoding incoming object request err %s %s", err, connection.logid) + connection.Exit() + } + + if len(request.Block_list) >= 1 { // handle incoming blocks list + for i := range request.Block_list { // + if !chain.Is_Block_Topological_order(request.Block_list[i]) { // block is not in our chain + if !chain.Block_Exists(request.Block_list[i]) { // check whether the block can be loaded from disk + response.Block_list = append(response.Block_list, request.Block_list[i]) + blids = append(blids, request.Block_list[i]) + dirty = true + } + } + } + } + + if len(request.Tx_list) >= 1 { // handle incoming tx list and see whether it exists in mempoolor regpool + for i := range request.Tx_list { // + if !(chain.Mempool.Mempool_TX_Exist(request.Tx_list[i]) || chain.Regpool.Regpool_TX_Exist(request.Tx_list[i])) { // check if is already in mempool skip it + if _, err = chain.Store.Block_tx_store.ReadTX(request.Tx_list[i]); err != nil { // check whether the tx can be loaded from disk + response.Tx_list = append(response.Tx_list, request.Tx_list[i]) + txids = append(txids, request.Tx_list[i]) + dirty = true + } + } + } + } + + if dirty { // request inventory only if we want it + fill_common(&response.Common) // fill common info + response.Command = V2_COMMAND_OBJECTS_REQUEST + serialized, err := msgpack.Marshal(&response) // serialize and send + if err != nil { + panic(err) + } + + command := Queued_Command{Command: V2_COMMAND_OBJECTS_RESPONSE, BLID: blids, TXID: txids} + connection.Objects <- command + atomic.StoreInt64(&connection.LastObjectRequestTime, time.Now().Unix()) + + rlog.Tracef(3, "OBJECT REQUEST SENT sent size %d %s", len(serialized), connection.logid) + connection.Send_Message(serialized) + } + +} diff --git a/p2p/object_request.go b/p2p/object_request.go index 6962b39..a288d47 100644 --- a/p2p/object_request.go +++ b/p2p/object_request.go @@ -87,30 +87,37 @@ func (connection *Connection) Handle_ObjectRequest(buf []byte) { connection.Exit() } - if len(request.Block_list) < 1 { // we are expecting 1 block + if len(request.Block_list) < 1 && len(request.Tx_list) < 1 { // we are expecting 1 block or 1 tx rlog.Warnf("malformed object request received, banning peer %+v %s", request, connection.logid) connection.Exit() } - for i := 0; i < len(request.Block_list); i++ { // find the common point in our chain + for i := range request.Block_list { // find the common point in our chain var cbl Complete_Block - if chain.Is_Block_Topological_order(request.Block_list[i]) { - bl, _ := chain.Load_BL_FROM_ID(request.Block_list[i]) - cbl.Block = bl.Serialize() - for j := range bl.Tx_hashes { - var tx_bytes []byte - if tx_bytes, err = chain.Store.Block_tx_store.ReadTX(bl.Tx_hashes[j]); err != nil { - return - } - cbl.Txs = append(cbl.Txs, tx_bytes) // append all the txs - + bl, _ := chain.Load_BL_FROM_ID(request.Block_list[i]) + cbl.Block = bl.Serialize() + for j := range bl.Tx_hashes { + var tx_bytes []byte + if tx_bytes, err = chain.Store.Block_tx_store.ReadTX(bl.Tx_hashes[j]); err != nil { + return } - } + cbl.Txs = append(cbl.Txs, tx_bytes) // append all the txs + } response.CBlocks = append(response.CBlocks, cbl) } - // we can serve maximum of 1024 BLID = 32 KB + for i := range request.Tx_list { // find the common point in our chain + var tx_bytes []byte + if tx := chain.Mempool.Mempool_Get_TX(request.Tx_list[i]); tx != nil { // if tx can be satisfied from pool, so be it + tx_bytes = tx.Serialize() + } else if tx := chain.Regpool.Regpool_Get_TX(request.Tx_list[i]); tx != nil { // if tx can be satisfied from regpool, so be it + tx_bytes = tx.Serialize() + } else if tx_bytes, err = chain.Store.Block_tx_store.ReadTX(request.Tx_list[i]); err != nil { + return + } + response.Txs = append(response.Txs, tx_bytes) // append all the txs + } // if everything is OK, we must respond with object response fill_common(&response.Common) // fill common info diff --git a/p2p/object_response.go b/p2p/object_response.go index bb91c11..7e7b5c6 100644 --- a/p2p/object_response.go +++ b/p2p/object_response.go @@ -65,6 +65,10 @@ func (connection *Connection) Handle_ObjectResponse(buf []byte) { rlog.Warnf("we got %d response for %d requests %s %s", len(response.CBlocks), len(expected.BLID), connection.logid) } + if len(response.Txs) != len(expected.TXID) { // we requested x block , peer sent us y blocks, time to ban peer + rlog.Warnf("we got %d response for %d requests %s %s", len(response.CBlocks), len(expected.BLID), connection.logid) + } + for i := 0; i < len(response.CBlocks); i++ { // process incoming full blocks var cbl block.Complete_Block // parse incoming block and deserialize it var bl block.Block @@ -107,6 +111,12 @@ func (connection *Connection) Handle_ObjectResponse(buf []byte) { if !ok && err == errormsg.ErrInvalidPoW { connection.logger.Warnf("This peer should be banned") connection.Exit() + return + } + + if !ok && err == errormsg.ErrPastMissing { + rlog.Warnf("Error Incoming Block coould not be added due to missing past, so skipping future block err %s %s", err, connection.logid) + return } // add the object to object pool from where it will be consume @@ -114,4 +124,18 @@ func (connection *Connection) Handle_ObjectResponse(buf []byte) { } + for i := range response.Txs { // process incoming txs for mempool + if !chain.Mempool.Mempool_TX_Exist(expected.TXID[i]) { // we still donot have it, so try to process it + var tx transaction.Transaction + err = tx.DeserializeHeader(response.Txs[i]) + if err != nil { // we have a tx which could not be deserialized ban peer + rlog.Warnf("Error Incoming TX could not be deserialized err %s %s", err, connection.logid) + connection.Exit() + + return + } + chain.Add_TX_To_Pool(&tx) // currently we are ignoring error + } + } + } diff --git a/p2p/wire_structs.go b/p2p/wire_structs.go index aaa2353..d9a45cf 100644 --- a/p2p/wire_structs.go +++ b/p2p/wire_structs.go @@ -41,13 +41,16 @@ const V2_COMMAND_OBJECTS_RESPONSE = 46 const V2_NOTIFY_NEW_BLOCK = 0xff // Notifications are asyncronous all notifications come here, such as new block, new txs const V2_NOTIFY_NEW_TX = 0xfe // notify tx using this +const V2_NOTIFY_INVENTORY = 0xfd // notify inventory that we have a new tx, or block +// this has the same structure V2_COMMAND_OBJECTS_REQUEST // used to parse incoming packet for for command , so as a repective command command could be triggered type Common_Struct struct { - Height int64 `msgpack:"HEIGHT"` - TopoHeight int64 `msgpack:"THEIGHT"` - StableHeight int64 `msgpack:"SHEIGHT"` - Cumulative_Difficulty string `msgpack:"CDIFF"` + Height int64 `msgpack:"HEIGHT"` + TopoHeight int64 `msgpack:"THEIGHT"` + StableHeight int64 `msgpack:"SHEIGHT"` + Cumulative_Difficulty string `msgpack:"CDIFF"` + StateHash [32]byte `msgpack:"STATE"` // Top_ID [32]byte `msgpack:"TOP"` // 32 bytes of Top block Top_Version uint64 `msgpack:"HF"` // this basically represents the hard fork version } @@ -64,6 +67,7 @@ type Handshake_Struct struct { UTC_Time int64 `msgpack:"UTC"` Local_Port uint32 `msgpack:"LP"` Peer_ID uint64 `msgpack:"PID"` + Pruned int64 `msgpack:"PRUNED"` Network_ID [16]byte `msgpack:"NID"` // 16 bytes Flags []string `msgpack:"FLAGS"` PeerList []Peer_Info `msgpack:"PLIST"` @@ -103,6 +107,7 @@ type Chain_Response_Struct struct { // peers gives us point where to get the cha } +// also used by V2_NOTIFY_INVENTORY type Object_Request_Struct struct { Command uint64 `msgpack:"COMMAND"` Common Common_Struct `msgpack:"COMMON"` // add all fields of Common diff --git a/vendor/github.com/coreos/bbolt/.gitignore b/vendor/github.com/coreos/bbolt/.gitignore deleted file mode 100644 index c2a8cfa..0000000 --- a/vendor/github.com/coreos/bbolt/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.prof -*.test -*.swp -/bin/ -cmd/bolt/bolt diff --git a/vendor/github.com/coreos/bbolt/LICENSE b/vendor/github.com/coreos/bbolt/LICENSE deleted file mode 100644 index 004e77f..0000000 --- a/vendor/github.com/coreos/bbolt/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Ben Johnson - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/coreos/bbolt/Makefile b/vendor/github.com/coreos/bbolt/Makefile deleted file mode 100644 index 43b94f3..0000000 --- a/vendor/github.com/coreos/bbolt/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -BRANCH=`git rev-parse --abbrev-ref HEAD` -COMMIT=`git rev-parse --short HEAD` -GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)" - -default: build - -race: - @go test -v -race -test.run="TestSimulate_(100op|1000op)" - -fmt: - !(gofmt -l -s -d $(shell find . -name \*.go) | grep '[a-z]') - -# go get honnef.co/go/tools/simple -gosimple: - gosimple ./... - -# go get honnef.co/go/tools/unused -unused: - unused ./... - -# go get github.com/kisielk/errcheck -errcheck: - @errcheck -ignorepkg=bytes -ignore=os:Remove github.com/coreos/bbolt - -test: - go test -timeout 20m -v -coverprofile cover.out -covermode atomic - # Note: gets "program not an importable package" in out of path builds - go test -v ./cmd/bolt - -.PHONY: race fmt errcheck test gosimple unused diff --git a/vendor/github.com/coreos/bbolt/README.md b/vendor/github.com/coreos/bbolt/README.md deleted file mode 100644 index 015f0ef..0000000 --- a/vendor/github.com/coreos/bbolt/README.md +++ /dev/null @@ -1,928 +0,0 @@ -bbolt -==== - -[![Go Report Card](https://goreportcard.com/badge/github.com/coreos/bbolt?style=flat-square)](https://goreportcard.com/report/github.com/coreos/bbolt) -[![Coverage](https://codecov.io/gh/coreos/bbolt/branch/master/graph/badge.svg)](https://codecov.io/gh/coreos/bbolt) -[![Godoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://godoc.org/github.com/coreos/bbolt) - -bbolt is a fork of [Ben Johnson's][gh_ben] [Bolt][bolt] key/value -store. The purpose of this fork is to provide the Go community with an active -maintenance and development target for Bolt; the goal is improved reliability -and stability. bbolt includes bug fixes, performance enhancements, and features -not found in Bolt while preserving backwards compatibility with the Bolt API. - -Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas] -[LMDB project][lmdb]. The goal of the project is to provide a simple, -fast, and reliable database for projects that don't require a full database -server such as Postgres or MySQL. - -Since Bolt is meant to be used as such a low-level piece of functionality, -simplicity is key. The API will be small and only focus on getting values -and setting values. That's it. - -[gh_ben]: https://github.com/benbjohnson -[bolt]: https://github.com/boltdb/bolt -[hyc_symas]: https://twitter.com/hyc_symas -[lmdb]: http://symas.com/mdb/ - -## Project Status - -Bolt is stable, the API is fixed, and the file format is fixed. Full unit -test coverage and randomized black box testing are used to ensure database -consistency and thread safety. Bolt is currently used in high-load production -environments serving databases as large as 1TB. Many companies such as -Shopify and Heroku use Bolt-backed services every day. - -## Table of Contents - -- [Getting Started](#getting-started) - - [Installing](#installing) - - [Opening a database](#opening-a-database) - - [Transactions](#transactions) - - [Read-write transactions](#read-write-transactions) - - [Read-only transactions](#read-only-transactions) - - [Batch read-write transactions](#batch-read-write-transactions) - - [Managing transactions manually](#managing-transactions-manually) - - [Using buckets](#using-buckets) - - [Using key/value pairs](#using-keyvalue-pairs) - - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket) - - [Iterating over keys](#iterating-over-keys) - - [Prefix scans](#prefix-scans) - - [Range scans](#range-scans) - - [ForEach()](#foreach) - - [Nested buckets](#nested-buckets) - - [Database backups](#database-backups) - - [Statistics](#statistics) - - [Read-Only Mode](#read-only-mode) - - [Mobile Use (iOS/Android)](#mobile-use-iosandroid) -- [Resources](#resources) -- [Comparison with other databases](#comparison-with-other-databases) - - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases) - - [LevelDB, RocksDB](#leveldb-rocksdb) - - [LMDB](#lmdb) -- [Caveats & Limitations](#caveats--limitations) -- [Reading the Source](#reading-the-source) -- [Other Projects Using Bolt](#other-projects-using-bolt) - -## Getting Started - -### Installing - -To start using Bolt, install Go and run `go get`: - -```sh -$ go get github.com/coreos/bbolt/... -``` - -This will retrieve the library and install the `bolt` command line utility into -your `$GOBIN` path. - - -### Opening a database - -The top-level object in Bolt is a `DB`. It is represented as a single file on -your disk and represents a consistent snapshot of your data. - -To open your database, simply use the `bolt.Open()` function: - -```go -package main - -import ( - "log" - - bolt "github.com/coreos/bbolt" -) - -func main() { - // Open the my.db data file in your current directory. - // It will be created if it doesn't exist. - db, err := bolt.Open("my.db", 0600, nil) - if err != nil { - log.Fatal(err) - } - defer db.Close() - - ... -} -``` - -Please note that Bolt obtains a file lock on the data file so multiple processes -cannot open the same database at the same time. Opening an already open Bolt -database will cause it to hang until the other process closes it. To prevent -an indefinite wait you can pass a timeout option to the `Open()` function: - -```go -db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}) -``` - - -### Transactions - -Bolt allows only one read-write transaction at a time but allows as many -read-only transactions as you want at a time. Each transaction has a consistent -view of the data as it existed when the transaction started. - -Individual transactions and all objects created from them (e.g. buckets, keys) -are not thread safe. To work with data in multiple goroutines you must start -a transaction for each one or use locking to ensure only one goroutine accesses -a transaction at a time. Creating transaction from the `DB` is thread safe. - -Read-only transactions and read-write transactions should not depend on one -another and generally shouldn't be opened simultaneously in the same goroutine. -This can cause a deadlock as the read-write transaction needs to periodically -re-map the data file but it cannot do so while a read-only transaction is open. - - -#### Read-write transactions - -To start a read-write transaction, you can use the `DB.Update()` function: - -```go -err := db.Update(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -Inside the closure, you have a consistent view of the database. You commit the -transaction by returning `nil` at the end. You can also rollback the transaction -at any point by returning an error. All database operations are allowed inside -a read-write transaction. - -Always check the return error as it will report any disk failures that can cause -your transaction to not complete. If you return an error within your closure -it will be passed through. - - -#### Read-only transactions - -To start a read-only transaction, you can use the `DB.View()` function: - -```go -err := db.View(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -You also get a consistent view of the database within this closure, however, -no mutating operations are allowed within a read-only transaction. You can only -retrieve buckets, retrieve values, and copy the database within a read-only -transaction. - - -#### Batch read-write transactions - -Each `DB.Update()` waits for disk to commit the writes. This overhead -can be minimized by combining multiple updates with the `DB.Batch()` -function: - -```go -err := db.Batch(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -Concurrent Batch calls are opportunistically combined into larger -transactions. Batch is only useful when there are multiple goroutines -calling it. - -The trade-off is that `Batch` can call the given -function multiple times, if parts of the transaction fail. The -function must be idempotent and side effects must take effect only -after a successful return from `DB.Batch()`. - -For example: don't display messages from inside the function, instead -set variables in the enclosing scope: - -```go -var id uint64 -err := db.Batch(func(tx *bolt.Tx) error { - // Find last key in bucket, decode as bigendian uint64, increment - // by one, encode back to []byte, and add new key. - ... - id = newValue - return nil -}) -if err != nil { - return ... -} -fmt.Println("Allocated ID %d", id) -``` - - -#### Managing transactions manually - -The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()` -function. These helper functions will start the transaction, execute a function, -and then safely close your transaction if an error is returned. This is the -recommended way to use Bolt transactions. - -However, sometimes you may want to manually start and end your transactions. -You can use the `DB.Begin()` function directly but **please** be sure to close -the transaction. - -```go -// Start a writable transaction. -tx, err := db.Begin(true) -if err != nil { - return err -} -defer tx.Rollback() - -// Use the transaction... -_, err := tx.CreateBucket([]byte("MyBucket")) -if err != nil { - return err -} - -// Commit the transaction and check for error. -if err := tx.Commit(); err != nil { - return err -} -``` - -The first argument to `DB.Begin()` is a boolean stating if the transaction -should be writable. - - -### Using buckets - -Buckets are collections of key/value pairs within the database. All keys in a -bucket must be unique. You can create a bucket using the `DB.CreateBucket()` -function: - -```go -db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("MyBucket")) - if err != nil { - return fmt.Errorf("create bucket: %s", err) - } - return nil -}) -``` - -You can also create a bucket only if it doesn't exist by using the -`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this -function for all your top-level buckets after you open your database so you can -guarantee that they exist for future transactions. - -To delete a bucket, simply call the `Tx.DeleteBucket()` function. - - -### Using key/value pairs - -To save a key/value pair to a bucket, use the `Bucket.Put()` function: - -```go -db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("MyBucket")) - err := b.Put([]byte("answer"), []byte("42")) - return err -}) -``` - -This will set the value of the `"answer"` key to `"42"` in the `MyBucket` -bucket. To retrieve this value, we can use the `Bucket.Get()` function: - -```go -db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("MyBucket")) - v := b.Get([]byte("answer")) - fmt.Printf("The answer is: %s\n", v) - return nil -}) -``` - -The `Get()` function does not return an error because its operation is -guaranteed to work (unless there is some kind of system failure). If the key -exists then it will return its byte slice value. If it doesn't exist then it -will return `nil`. It's important to note that you can have a zero-length value -set to a key which is different than the key not existing. - -Use the `Bucket.Delete()` function to delete a key from the bucket. - -Please note that values returned from `Get()` are only valid while the -transaction is open. If you need to use a value outside of the transaction -then you must use `copy()` to copy it to another byte slice. - - -### Autoincrementing integer for the bucket -By using the `NextSequence()` function, you can let Bolt determine a sequence -which can be used as the unique identifier for your key/value pairs. See the -example below. - -```go -// CreateUser saves u to the store. The new user ID is set on u once the data is persisted. -func (s *Store) CreateUser(u *User) error { - return s.db.Update(func(tx *bolt.Tx) error { - // Retrieve the users bucket. - // This should be created when the DB is first opened. - b := tx.Bucket([]byte("users")) - - // Generate ID for the user. - // This returns an error only if the Tx is closed or not writeable. - // That can't happen in an Update() call so I ignore the error check. - id, _ := b.NextSequence() - u.ID = int(id) - - // Marshal user data into bytes. - buf, err := json.Marshal(u) - if err != nil { - return err - } - - // Persist bytes to users bucket. - return b.Put(itob(u.ID), buf) - }) -} - -// itob returns an 8-byte big endian representation of v. -func itob(v int) []byte { - b := make([]byte, 8) - binary.BigEndian.PutUint64(b, uint64(v)) - return b -} - -type User struct { - ID int - ... -} -``` - -### Iterating over keys - -Bolt stores its keys in byte-sorted order within a bucket. This makes sequential -iteration over these keys extremely fast. To iterate over keys we'll use a -`Cursor`: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - b := tx.Bucket([]byte("MyBucket")) - - c := b.Cursor() - - for k, v := c.First(); k != nil; k, v = c.Next() { - fmt.Printf("key=%s, value=%s\n", k, v) - } - - return nil -}) -``` - -The cursor allows you to move to a specific point in the list of keys and move -forward or backward through the keys one at a time. - -The following functions are available on the cursor: - -``` -First() Move to the first key. -Last() Move to the last key. -Seek() Move to a specific key. -Next() Move to the next key. -Prev() Move to the previous key. -``` - -Each of those functions has a return signature of `(key []byte, value []byte)`. -When you have iterated to the end of the cursor then `Next()` will return a -`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()` -before calling `Next()` or `Prev()`. If you do not seek to a position then -these functions will return a `nil` key. - -During iteration, if the key is non-`nil` but the value is `nil`, that means -the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to -access the sub-bucket. - - -#### Prefix scans - -To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - c := tx.Bucket([]byte("MyBucket")).Cursor() - - prefix := []byte("1234") - for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { - fmt.Printf("key=%s, value=%s\n", k, v) - } - - return nil -}) -``` - -#### Range scans - -Another common use case is scanning over a range such as a time range. If you -use a sortable time encoding such as RFC3339 then you can query a specific -date range like this: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume our events bucket exists and has RFC3339 encoded time keys. - c := tx.Bucket([]byte("Events")).Cursor() - - // Our time range spans the 90's decade. - min := []byte("1990-01-01T00:00:00Z") - max := []byte("2000-01-01T00:00:00Z") - - // Iterate over the 90's. - for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() { - fmt.Printf("%s: %s\n", k, v) - } - - return nil -}) -``` - -Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable. - - -#### ForEach() - -You can also use the function `ForEach()` if you know you'll be iterating over -all the keys in a bucket: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - b := tx.Bucket([]byte("MyBucket")) - - b.ForEach(func(k, v []byte) error { - fmt.Printf("key=%s, value=%s\n", k, v) - return nil - }) - return nil -}) -``` - -Please note that keys and values in `ForEach()` are only valid while -the transaction is open. If you need to use a key or value outside of -the transaction, you must use `copy()` to copy it to another byte -slice. - -### Nested buckets - -You can also store a bucket in a key to create nested buckets. The API is the -same as the bucket management API on the `DB` object: - -```go -func (*Bucket) CreateBucket(key []byte) (*Bucket, error) -func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) -func (*Bucket) DeleteBucket(key []byte) error -``` - -Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings. - -```go - -// createUser creates a new user in the given account. -func createUser(accountID int, u *User) error { - // Start the transaction. - tx, err := db.Begin(true) - if err != nil { - return err - } - defer tx.Rollback() - - // Retrieve the root bucket for the account. - // Assume this has already been created when the account was set up. - root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10))) - - // Setup the users bucket. - bkt, err := root.CreateBucketIfNotExists([]byte("USERS")) - if err != nil { - return err - } - - // Generate an ID for the new user. - userID, err := bkt.NextSequence() - if err != nil { - return err - } - u.ID = userID - - // Marshal and save the encoded user. - if buf, err := json.Marshal(u); err != nil { - return err - } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil { - return err - } - - // Commit the transaction. - if err := tx.Commit(); err != nil { - return err - } - - return nil -} - -``` - - - - -### Database backups - -Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()` -function to write a consistent view of the database to a writer. If you call -this from a read-only transaction, it will perform a hot backup and not block -your other database reads and writes. - -By default, it will use a regular file handle which will utilize the operating -system's page cache. See the [`Tx`](https://godoc.org/github.com/coreos/bbolt#Tx) -documentation for information about optimizing for larger-than-RAM datasets. - -One common use case is to backup over HTTP so you can use tools like `cURL` to -do database backups: - -```go -func BackupHandleFunc(w http.ResponseWriter, req *http.Request) { - err := db.View(func(tx *bolt.Tx) error { - w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Disposition", `attachment; filename="my.db"`) - w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size()))) - _, err := tx.WriteTo(w) - return err - }) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} -``` - -Then you can backup using this command: - -```sh -$ curl http://localhost/backup > my.db -``` - -Or you can open your browser to `http://localhost/backup` and it will download -automatically. - -If you want to backup to another file you can use the `Tx.CopyFile()` helper -function. - - -### Statistics - -The database keeps a running count of many of the internal operations it -performs so you can better understand what's going on. By grabbing a snapshot -of these stats at two points in time we can see what operations were performed -in that time range. - -For example, we could start a goroutine to log stats every 10 seconds: - -```go -go func() { - // Grab the initial stats. - prev := db.Stats() - - for { - // Wait for 10s. - time.Sleep(10 * time.Second) - - // Grab the current stats and diff them. - stats := db.Stats() - diff := stats.Sub(&prev) - - // Encode stats to JSON and print to STDERR. - json.NewEncoder(os.Stderr).Encode(diff) - - // Save stats for the next loop. - prev = stats - } -}() -``` - -It's also useful to pipe these stats to a service such as statsd for monitoring -or to provide an HTTP endpoint that will perform a fixed-length sample. - - -### Read-Only Mode - -Sometimes it is useful to create a shared, read-only Bolt database. To this, -set the `Options.ReadOnly` flag when opening your database. Read-only mode -uses a shared lock to allow multiple processes to read from the database but -it will block any processes from opening the database in read-write mode. - -```go -db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true}) -if err != nil { - log.Fatal(err) -} -``` - -### Mobile Use (iOS/Android) - -Bolt is able to run on mobile devices by leveraging the binding feature of the -[gomobile](https://github.com/golang/mobile) tool. Create a struct that will -contain your database logic and a reference to a `*bolt.DB` with a initializing -constructor that takes in a filepath where the database file will be stored. -Neither Android nor iOS require extra permissions or cleanup from using this method. - -```go -func NewBoltDB(filepath string) *BoltDB { - db, err := bolt.Open(filepath+"/demo.db", 0600, nil) - if err != nil { - log.Fatal(err) - } - - return &BoltDB{db} -} - -type BoltDB struct { - db *bolt.DB - ... -} - -func (b *BoltDB) Path() string { - return b.db.Path() -} - -func (b *BoltDB) Close() { - b.db.Close() -} -``` - -Database logic should be defined as methods on this wrapper struct. - -To initialize this struct from the native language (both platforms now sync -their local storage to the cloud. These snippets disable that functionality for the -database file): - -#### Android - -```java -String path; -if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){ - path = getNoBackupFilesDir().getAbsolutePath(); -} else{ - path = getFilesDir().getAbsolutePath(); -} -Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path) -``` - -#### iOS - -```objc -- (void)demo { - NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, - NSUserDomainMask, - YES) objectAtIndex:0]; - GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path); - [self addSkipBackupAttributeToItemAtPath:demo.path]; - //Some DB Logic would go here - [demo close]; -} - -- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString -{ - NSURL* URL= [NSURL fileURLWithPath: filePathString]; - assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]); - - NSError *error = nil; - BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES] - forKey: NSURLIsExcludedFromBackupKey error: &error]; - if(!success){ - NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); - } - return success; -} - -``` - -## Resources - -For more information on getting started with Bolt, check out the following articles: - -* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch). -* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville - - -## Comparison with other databases - -### Postgres, MySQL, & other relational databases - -Relational databases structure data into rows and are only accessible through -the use of SQL. This approach provides flexibility in how you store and query -your data but also incurs overhead in parsing and planning SQL statements. Bolt -accesses all data by a byte slice key. This makes Bolt fast to read and write -data by key but provides no built-in support for joining values together. - -Most relational databases (with the exception of SQLite) are standalone servers -that run separately from your application. This gives your systems -flexibility to connect multiple application servers to a single database -server but also adds overhead in serializing and transporting data over the -network. Bolt runs as a library included in your application so all data access -has to go through your application's process. This brings data closer to your -application but limits multi-process access to the data. - - -### LevelDB, RocksDB - -LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that -they are libraries bundled into the application, however, their underlying -structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes -random writes by using a write ahead log and multi-tiered, sorted files called -SSTables. Bolt uses a B+tree internally and only a single file. Both approaches -have trade-offs. - -If you require a high random write throughput (>10,000 w/sec) or you need to use -spinning disks then LevelDB could be a good choice. If your application is -read-heavy or does a lot of range scans then Bolt could be a good choice. - -One other important consideration is that LevelDB does not have transactions. -It supports batch writing of key/values pairs and it supports read snapshots -but it will not give you the ability to do a compare-and-swap operation safely. -Bolt supports fully serializable ACID transactions. - - -### LMDB - -Bolt was originally a port of LMDB so it is architecturally similar. Both use -a B+tree, have ACID semantics with fully serializable transactions, and support -lock-free MVCC using a single writer and multiple readers. - -The two projects have somewhat diverged. LMDB heavily focuses on raw performance -while Bolt has focused on simplicity and ease of use. For example, LMDB allows -several unsafe actions such as direct writes for the sake of performance. Bolt -opts to disallow actions which can leave the database in a corrupted state. The -only exception to this in Bolt is `DB.NoSync`. - -There are also a few differences in API. LMDB requires a maximum mmap size when -opening an `mdb_env` whereas Bolt will handle incremental mmap resizing -automatically. LMDB overloads the getter and setter functions with multiple -flags whereas Bolt splits these specialized cases into their own functions. - - -## Caveats & Limitations - -It's important to pick the right tool for the job and Bolt is no exception. -Here are a few things to note when evaluating and using Bolt: - -* Bolt is good for read intensive workloads. Sequential write performance is - also fast but random writes can be slow. You can use `DB.Batch()` or add a - write-ahead log to help mitigate this issue. - -* Bolt uses a B+tree internally so there can be a lot of random page access. - SSDs provide a significant performance boost over spinning disks. - -* Try to avoid long running read transactions. Bolt uses copy-on-write so - old pages cannot be reclaimed while an old transaction is using them. - -* Byte slices returned from Bolt are only valid during a transaction. Once the - transaction has been committed or rolled back then the memory they point to - can be reused by a new page or can be unmapped from virtual memory and you'll - see an `unexpected fault address` panic when accessing it. - -* Bolt uses an exclusive write lock on the database file so it cannot be - shared by multiple processes. - -* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for - buckets that have random inserts will cause your database to have very poor - page utilization. - -* Use larger buckets in general. Smaller buckets causes poor page utilization - once they become larger than the page size (typically 4KB). - -* Bulk loading a lot of random writes into a new bucket can be slow as the - page will not split until the transaction is committed. Randomly inserting - more than 100,000 key/value pairs into a single new bucket in a single - transaction is not advised. - -* Bolt uses a memory-mapped file so the underlying operating system handles the - caching of the data. Typically, the OS will cache as much of the file as it - can in memory and will release memory as needed to other processes. This means - that Bolt can show very high memory usage when working with large databases. - However, this is expected and the OS will release memory as needed. Bolt can - handle databases much larger than the available physical RAM, provided its - memory-map fits in the process virtual address space. It may be problematic - on 32-bits systems. - -* The data structures in the Bolt database are memory mapped so the data file - will be endian specific. This means that you cannot copy a Bolt file from a - little endian machine to a big endian machine and have it work. For most - users this is not a concern since most modern CPUs are little endian. - -* Because of the way pages are laid out on disk, Bolt cannot truncate data files - and return free pages back to the disk. Instead, Bolt maintains a free list - of unused pages within its data file. These free pages can be reused by later - transactions. This works well for many use cases as databases generally tend - to grow. However, it's important to note that deleting large chunks of data - will not allow you to reclaim that space on disk. - - For more information on page allocation, [see this comment][page-allocation]. - -[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638 - - -## Reading the Source - -Bolt is a relatively small code base (<5KLOC) for an embedded, serializable, -transactional key/value database so it can be a good starting point for people -interested in how databases work. - -The best places to start are the main entry points into Bolt: - -- `Open()` - Initializes the reference to the database. It's responsible for - creating the database if it doesn't exist, obtaining an exclusive lock on the - file, reading the meta pages, & memory-mapping the file. - -- `DB.Begin()` - Starts a read-only or read-write transaction depending on the - value of the `writable` argument. This requires briefly obtaining the "meta" - lock to keep track of open transactions. Only one read-write transaction can - exist at a time so the "rwlock" is acquired during the life of a read-write - transaction. - -- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the - arguments, a cursor is used to traverse the B+tree to the page and position - where they key & value will be written. Once the position is found, the bucket - materializes the underlying page and the page's parent pages into memory as - "nodes". These nodes are where mutations occur during read-write transactions. - These changes get flushed to disk during commit. - -- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor - to move to the page & position of a key/value pair. During a read-only - transaction, the key and value data is returned as a direct reference to the - underlying mmap file so there's no allocation overhead. For read-write - transactions, this data may reference the mmap file or one of the in-memory - node values. - -- `Cursor` - This object is simply for traversing the B+tree of on-disk pages - or in-memory nodes. It can seek to a specific key, move to the first or last - value, or it can move forward or backward. The cursor handles the movement up - and down the B+tree transparently to the end user. - -- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages - into pages to be written to disk. Writing to disk then occurs in two phases. - First, the dirty pages are written to disk and an `fsync()` occurs. Second, a - new meta page with an incremented transaction ID is written and another - `fsync()` occurs. This two phase write ensures that partially written data - pages are ignored in the event of a crash since the meta page pointing to them - is never written. Partially written meta pages are invalidated because they - are written with a checksum. - -If you have additional notes that could be helpful for others, please submit -them via pull request. - - -## Other Projects Using Bolt - -Below is a list of public, open source projects that use Bolt: - -* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files. -* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard. -* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside. -* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb. -* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics. -* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects. -* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday. -* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations. -* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite. -* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin". -* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka. -* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed. -* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt. -* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site. -* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage. -* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters. -* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend. -* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend. -* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server. -* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read. -* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics. -* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data. -* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system. -* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware. -* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs. -* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems. -* [stow](https://github.com/djherbis/stow) - a persistence manager for objects - backed by boltdb. -* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining - simple tx and key scans. -* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets. -* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service -* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service. -* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners. -* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores. -* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB. -* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB. -* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings. -* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend. -* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files. -* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter. -* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development. -* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains -* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal. -* [boltcli](https://github.com/spacewander/boltcli) - the redis-cli for boltdb with Lua script support. -* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet. -* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency. -* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies -* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB - -If you are using Bolt in a project please send a pull request to add it to the list. diff --git a/vendor/github.com/coreos/bbolt/allocate_test.go b/vendor/github.com/coreos/bbolt/allocate_test.go deleted file mode 100644 index 8566b4d..0000000 --- a/vendor/github.com/coreos/bbolt/allocate_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package bolt - -import ( - "testing" -) - -func TestTx_allocatePageStats(t *testing.T) { - f := newFreelist() - f.ids = []pgid{2, 3} - - tx := &Tx{ - db: &DB{ - freelist: f, - pageSize: defaultPageSize, - }, - meta: &meta{}, - pages: make(map[pgid]*page), - } - - prePageCnt := tx.Stats().PageCount - allocateCnt := f.free_count() - - if _, err := tx.allocate(allocateCnt); err != nil { - t.Fatal(err) - } - - if tx.Stats().PageCount != prePageCnt+allocateCnt { - t.Errorf("Allocated %d but got %d page in stats", allocateCnt, tx.Stats().PageCount) - } -} diff --git a/vendor/github.com/coreos/bbolt/appveyor.yml b/vendor/github.com/coreos/bbolt/appveyor.yml deleted file mode 100644 index 6e26e94..0000000 --- a/vendor/github.com/coreos/bbolt/appveyor.yml +++ /dev/null @@ -1,18 +0,0 @@ -version: "{build}" - -os: Windows Server 2012 R2 - -clone_folder: c:\gopath\src\github.com\boltdb\bolt - -environment: - GOPATH: c:\gopath - -install: - - echo %PATH% - - echo %GOPATH% - - go version - - go env - - go get -v -t ./... - -build_script: - - go test -v ./... diff --git a/vendor/github.com/coreos/bbolt/bolt_386.go b/vendor/github.com/coreos/bbolt/bolt_386.go deleted file mode 100644 index 820d533..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_386.go +++ /dev/null @@ -1,10 +0,0 @@ -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x7FFFFFFF // 2GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0xFFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_amd64.go b/vendor/github.com/coreos/bbolt/bolt_amd64.go deleted file mode 100644 index 98fafdb..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_amd64.go +++ /dev/null @@ -1,10 +0,0 @@ -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_arm.go b/vendor/github.com/coreos/bbolt/bolt_arm.go deleted file mode 100644 index 7e5cb4b..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_arm.go +++ /dev/null @@ -1,28 +0,0 @@ -package bolt - -import "unsafe" - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x7FFFFFFF // 2GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0xFFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned bool - -func init() { - // Simple check to see whether this arch handles unaligned load/stores - // correctly. - - // ARM9 and older devices require load/stores to be from/to aligned - // addresses. If not, the lower 2 bits are cleared and that address is - // read in a jumbled up order. - - // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html - - raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11} - val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2)) - - brokenUnaligned = val != 0x11222211 -} diff --git a/vendor/github.com/coreos/bbolt/bolt_arm64.go b/vendor/github.com/coreos/bbolt/bolt_arm64.go deleted file mode 100644 index b26d84f..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_arm64.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build arm64 - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_linux.go b/vendor/github.com/coreos/bbolt/bolt_linux.go deleted file mode 100644 index 2b67666..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_linux.go +++ /dev/null @@ -1,10 +0,0 @@ -package bolt - -import ( - "syscall" -) - -// fdatasync flushes written data to a file descriptor. -func fdatasync(db *DB) error { - return syscall.Fdatasync(int(db.file.Fd())) -} diff --git a/vendor/github.com/coreos/bbolt/bolt_mips64x.go b/vendor/github.com/coreos/bbolt/bolt_mips64x.go deleted file mode 100644 index 134b578..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_mips64x.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build mips64 mips64le - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x8000000000 // 512GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_mipsx.go b/vendor/github.com/coreos/bbolt/bolt_mipsx.go deleted file mode 100644 index d5ecb05..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_mipsx.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build mips mipsle - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x40000000 // 1GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0xFFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_openbsd.go b/vendor/github.com/coreos/bbolt/bolt_openbsd.go deleted file mode 100644 index 7058c3d..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_openbsd.go +++ /dev/null @@ -1,27 +0,0 @@ -package bolt - -import ( - "syscall" - "unsafe" -) - -const ( - msAsync = 1 << iota // perform asynchronous writes - msSync // perform synchronous writes - msInvalidate // invalidate cached data -) - -func msync(db *DB) error { - _, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate) - if errno != 0 { - return errno - } - return nil -} - -func fdatasync(db *DB) error { - if db.data != nil { - return msync(db) - } - return db.file.Sync() -} diff --git a/vendor/github.com/coreos/bbolt/bolt_ppc.go b/vendor/github.com/coreos/bbolt/bolt_ppc.go deleted file mode 100644 index 55cb8a7..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_ppc.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build ppc - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x7FFFFFFF // 2GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0xFFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_ppc64.go b/vendor/github.com/coreos/bbolt/bolt_ppc64.go deleted file mode 100644 index 9331d97..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_ppc64.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build ppc64 - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_ppc64le.go b/vendor/github.com/coreos/bbolt/bolt_ppc64le.go deleted file mode 100644 index 8c143bc..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_ppc64le.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build ppc64le - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_s390x.go b/vendor/github.com/coreos/bbolt/bolt_s390x.go deleted file mode 100644 index d7c39af..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_s390x.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build s390x - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/coreos/bbolt/bolt_unix.go b/vendor/github.com/coreos/bbolt/bolt_unix.go deleted file mode 100644 index add3bd8..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_unix.go +++ /dev/null @@ -1,94 +0,0 @@ -// +build !windows,!plan9,!solaris - -package bolt - -import ( - "fmt" - "os" - "syscall" - "time" - "unsafe" -) - -// flock acquires an advisory lock on a file descriptor. -func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { - var t time.Time - if timeout != 0 { - t = time.Now() - } - fd := db.file.Fd() - flag := syscall.LOCK_NB - if exclusive { - flag |= syscall.LOCK_EX - } else { - flag |= syscall.LOCK_SH - } - for { - // Attempt to obtain an exclusive lock. - err := syscall.Flock(int(fd), flag) - if err == nil { - return nil - } else if err != syscall.EWOULDBLOCK { - return err - } - - // If we timed out then return an error. - if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout { - return ErrTimeout - } - - // Wait for a bit and try again. - time.Sleep(flockRetryTimeout) - } -} - -// funlock releases an advisory lock on a file descriptor. -func funlock(db *DB) error { - return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN) -} - -// mmap memory maps a DB's data file. -func mmap(db *DB, sz int) error { - // Map the data file to memory. - b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) - if err != nil { - return err - } - - // Advise the kernel that the mmap is accessed randomly. - err = madvise(b, syscall.MADV_RANDOM) - if err != nil && err != syscall.ENOSYS { - // Ignore not implemented error in kernel because it still works. - return fmt.Errorf("madvise: %s", err) - } - - // Save the original byte slice and convert to a byte array pointer. - db.dataref = b - db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) - db.datasz = sz - return nil -} - -// munmap unmaps a DB's data file from memory. -func munmap(db *DB) error { - // Ignore the unmap if we have no mapped data. - if db.dataref == nil { - return nil - } - - // Unmap using the original byte slice. - err := syscall.Munmap(db.dataref) - db.dataref = nil - db.data = nil - db.datasz = 0 - return err -} - -// NOTE: This function is copied from stdlib because it is not available on darwin. -func madvise(b []byte, advice int) (err error) { - _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = e1 - } - return -} diff --git a/vendor/github.com/coreos/bbolt/bolt_unix_solaris.go b/vendor/github.com/coreos/bbolt/bolt_unix_solaris.go deleted file mode 100644 index fd8335e..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_unix_solaris.go +++ /dev/null @@ -1,89 +0,0 @@ -package bolt - -import ( - "fmt" - "os" - "syscall" - "time" - "unsafe" - - "golang.org/x/sys/unix" -) - -// flock acquires an advisory lock on a file descriptor. -func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { - var t time.Time - if timeout != 0 { - t = time.Now() - } - fd := db.file.Fd() - var lockType int16 - if exclusive { - lockType = syscall.F_WRLCK - } else { - lockType = syscall.F_RDLCK - } - for { - // Attempt to obtain an exclusive lock. - lock := syscall.Flock_t{Type: lockType} - err := syscall.FcntlFlock(fd, syscall.F_SETLK, &lock) - if err == nil { - return nil - } else if err != syscall.EAGAIN { - return err - } - - // If we timed out then return an error. - if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout { - return ErrTimeout - } - - // Wait for a bit and try again. - time.Sleep(flockRetryTimeout) - } -} - -// funlock releases an advisory lock on a file descriptor. -func funlock(db *DB) error { - var lock syscall.Flock_t - lock.Start = 0 - lock.Len = 0 - lock.Type = syscall.F_UNLCK - lock.Whence = 0 - return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock) -} - -// mmap memory maps a DB's data file. -func mmap(db *DB, sz int) error { - // Map the data file to memory. - b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) - if err != nil { - return err - } - - // Advise the kernel that the mmap is accessed randomly. - if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil { - return fmt.Errorf("madvise: %s", err) - } - - // Save the original byte slice and convert to a byte array pointer. - db.dataref = b - db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) - db.datasz = sz - return nil -} - -// munmap unmaps a DB's data file from memory. -func munmap(db *DB) error { - // Ignore the unmap if we have no mapped data. - if db.dataref == nil { - return nil - } - - // Unmap using the original byte slice. - err := unix.Munmap(db.dataref) - db.dataref = nil - db.data = nil - db.datasz = 0 - return err -} diff --git a/vendor/github.com/coreos/bbolt/bolt_windows.go b/vendor/github.com/coreos/bbolt/bolt_windows.go deleted file mode 100644 index ca6f9a1..0000000 --- a/vendor/github.com/coreos/bbolt/bolt_windows.go +++ /dev/null @@ -1,145 +0,0 @@ -package bolt - -import ( - "fmt" - "os" - "syscall" - "time" - "unsafe" -) - -// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1 -var ( - modkernel32 = syscall.NewLazyDLL("kernel32.dll") - procLockFileEx = modkernel32.NewProc("LockFileEx") - procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") -) - -const ( - lockExt = ".lock" - - // see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx - flagLockExclusive = 2 - flagLockFailImmediately = 1 - - // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx - errLockViolation syscall.Errno = 0x21 -) - -func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { - r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol))) - if r == 0 { - return err - } - return nil -} - -func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { - r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0) - if r == 0 { - return err - } - return nil -} - -// fdatasync flushes written data to a file descriptor. -func fdatasync(db *DB) error { - return db.file.Sync() -} - -// flock acquires an advisory lock on a file descriptor. -func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { - // Create a separate lock file on windows because a process - // cannot share an exclusive lock on the same file. This is - // needed during Tx.WriteTo(). - f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode) - if err != nil { - return err - } - db.lockfile = f - - var t time.Time - if timeout != 0 { - t = time.Now() - } - fd := f.Fd() - var flag uint32 = flagLockFailImmediately - if exclusive { - flag |= flagLockExclusive - } - for { - // Attempt to obtain an exclusive lock. - err := lockFileEx(syscall.Handle(fd), flag, 0, 1, 0, &syscall.Overlapped{}) - if err == nil { - return nil - } else if err != errLockViolation { - return err - } - - // If we timed oumercit then return an error. - if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout { - return ErrTimeout - } - - // Wait for a bit and try again. - time.Sleep(flockRetryTimeout) - } -} - -// funlock releases an advisory lock on a file descriptor. -func funlock(db *DB) error { - err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{}) - db.lockfile.Close() - os.Remove(db.path + lockExt) - return err -} - -// mmap memory maps a DB's data file. -// Based on: https://github.com/edsrzf/mmap-go -func mmap(db *DB, sz int) error { - if !db.readOnly { - // Truncate the database to the size of the mmap. - if err := db.file.Truncate(int64(sz)); err != nil { - return fmt.Errorf("truncate: %s", err) - } - } - - // Open a file mapping handle. - sizelo := uint32(sz >> 32) - sizehi := uint32(sz) & 0xffffffff - h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil) - if h == 0 { - return os.NewSyscallError("CreateFileMapping", errno) - } - - // Create the memory map. - addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz)) - if addr == 0 { - return os.NewSyscallError("MapViewOfFile", errno) - } - - // Close mapping handle. - if err := syscall.CloseHandle(syscall.Handle(h)); err != nil { - return os.NewSyscallError("CloseHandle", err) - } - - // Convert to a byte array. - db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr))) - db.datasz = sz - - return nil -} - -// munmap unmaps a pointer from a file. -// Based on: https://github.com/edsrzf/mmap-go -func munmap(db *DB) error { - if db.data == nil { - return nil - } - - addr := (uintptr)(unsafe.Pointer(&db.data[0])) - if err := syscall.UnmapViewOfFile(addr); err != nil { - return os.NewSyscallError("UnmapViewOfFile", err) - } - return nil -} diff --git a/vendor/github.com/coreos/bbolt/boltsync_unix.go b/vendor/github.com/coreos/bbolt/boltsync_unix.go deleted file mode 100644 index f504425..0000000 --- a/vendor/github.com/coreos/bbolt/boltsync_unix.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !windows,!plan9,!linux,!openbsd - -package bolt - -// fdatasync flushes written data to a file descriptor. -func fdatasync(db *DB) error { - return db.file.Sync() -} diff --git a/vendor/github.com/coreos/bbolt/bucket.go b/vendor/github.com/coreos/bbolt/bucket.go deleted file mode 100644 index 44db88b..0000000 --- a/vendor/github.com/coreos/bbolt/bucket.go +++ /dev/null @@ -1,775 +0,0 @@ -package bolt - -import ( - "bytes" - "fmt" - "unsafe" -) - -const ( - // MaxKeySize is the maximum length of a key, in bytes. - MaxKeySize = 32768 - - // MaxValueSize is the maximum length of a value, in bytes. - MaxValueSize = (1 << 31) - 2 -) - -const bucketHeaderSize = int(unsafe.Sizeof(bucket{})) - -const ( - minFillPercent = 0.1 - maxFillPercent = 1.0 -) - -// DefaultFillPercent is the percentage that split pages are filled. -// This value can be changed by setting Bucket.FillPercent. -const DefaultFillPercent = 0.5 - -// Bucket represents a collection of key/value pairs inside the database. -type Bucket struct { - *bucket - tx *Tx // the associated transaction - buckets map[string]*Bucket // subbucket cache - page *page // inline page reference - rootNode *node // materialized node for the root page. - nodes map[pgid]*node // node cache - - // Sets the threshold for filling nodes when they split. By default, - // the bucket will fill to 50% but it can be useful to increase this - // amount if you know that your write workloads are mostly append-only. - // - // This is non-persisted across transactions so it must be set in every Tx. - FillPercent float64 -} - -// bucket represents the on-file representation of a bucket. -// This is stored as the "value" of a bucket key. If the bucket is small enough, -// then its root page can be stored inline in the "value", after the bucket -// header. In the case of inline buckets, the "root" will be 0. -type bucket struct { - root pgid // page id of the bucket's root-level page - sequence uint64 // monotonically incrementing, used by NextSequence() -} - -// newBucket returns a new bucket associated with a transaction. -func newBucket(tx *Tx) Bucket { - var b = Bucket{tx: tx, FillPercent: DefaultFillPercent} - if tx.writable { - b.buckets = make(map[string]*Bucket) - b.nodes = make(map[pgid]*node) - } - return b -} - -// Tx returns the tx of the bucket. -func (b *Bucket) Tx() *Tx { - return b.tx -} - -// Root returns the root of the bucket. -func (b *Bucket) Root() pgid { - return b.root -} - -// Writable returns whether the bucket is writable. -func (b *Bucket) Writable() bool { - return b.tx.writable -} - -// Cursor creates a cursor associated with the bucket. -// The cursor is only valid as long as the transaction is open. -// Do not use a cursor after the transaction is closed. -func (b *Bucket) Cursor() *Cursor { - // Update transaction statistics. - b.tx.stats.CursorCount++ - - // Allocate and return a cursor. - return &Cursor{ - bucket: b, - stack: make([]elemRef, 0), - } -} - -// Bucket retrieves a nested bucket by name. -// Returns nil if the bucket does not exist. -// The bucket instance is only valid for the lifetime of the transaction. -func (b *Bucket) Bucket(name []byte) *Bucket { - if b.buckets != nil { - if child := b.buckets[string(name)]; child != nil { - return child - } - } - - // Move cursor to key. - c := b.Cursor() - k, v, flags := c.seek(name) - - // Return nil if the key doesn't exist or it is not a bucket. - if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 { - return nil - } - - // Otherwise create a bucket and cache it. - var child = b.openBucket(v) - if b.buckets != nil { - b.buckets[string(name)] = child - } - - return child -} - -// Helper method that re-interprets a sub-bucket value -// from a parent into a Bucket -func (b *Bucket) openBucket(value []byte) *Bucket { - var child = newBucket(b.tx) - - // If unaligned load/stores are broken on this arch and value is - // unaligned simply clone to an aligned byte array. - unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0 - - if unaligned { - value = cloneBytes(value) - } - - // If this is a writable transaction then we need to copy the bucket entry. - // Read-only transactions can point directly at the mmap entry. - if b.tx.writable && !unaligned { - child.bucket = &bucket{} - *child.bucket = *(*bucket)(unsafe.Pointer(&value[0])) - } else { - child.bucket = (*bucket)(unsafe.Pointer(&value[0])) - } - - // Save a reference to the inline page if the bucket is inline. - if child.root == 0 { - child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) - } - - return &child -} - -// CreateBucket creates a new bucket at the given key and returns the new bucket. -// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) { - if b.tx.db == nil { - return nil, ErrTxClosed - } else if !b.tx.writable { - return nil, ErrTxNotWritable - } else if len(key) == 0 { - return nil, ErrBucketNameRequired - } - - // Move cursor to correct position. - c := b.Cursor() - k, _, flags := c.seek(key) - - // Return an error if there is an existing key. - if bytes.Equal(key, k) { - if (flags & bucketLeafFlag) != 0 { - return nil, ErrBucketExists - } - return nil, ErrIncompatibleValue - } - - // Create empty, inline bucket. - var bucket = Bucket{ - bucket: &bucket{}, - rootNode: &node{isLeaf: true}, - FillPercent: DefaultFillPercent, - } - var value = bucket.write() - - // Insert into node. - key = cloneBytes(key) - c.node().put(key, key, value, 0, bucketLeafFlag) - - // Since subbuckets are not allowed on inline buckets, we need to - // dereference the inline page, if it exists. This will cause the bucket - // to be treated as a regular, non-inline bucket for the rest of the tx. - b.page = nil - - return b.Bucket(key), nil -} - -// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it. -// Returns an error if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) { - child, err := b.CreateBucket(key) - if err == ErrBucketExists { - return b.Bucket(key), nil - } else if err != nil { - return nil, err - } - return child, nil -} - -// DeleteBucket deletes a bucket at the given key. -// Returns an error if the bucket does not exists, or if the key represents a non-bucket value. -func (b *Bucket) DeleteBucket(key []byte) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } - - // Move cursor to correct position. - c := b.Cursor() - k, _, flags := c.seek(key) - - // Return an error if bucket doesn't exist or is not a bucket. - if !bytes.Equal(key, k) { - return ErrBucketNotFound - } else if (flags & bucketLeafFlag) == 0 { - return ErrIncompatibleValue - } - - // Recursively delete all child buckets. - child := b.Bucket(key) - err := child.ForEach(func(k, v []byte) error { - if v == nil { - if err := child.DeleteBucket(k); err != nil { - return fmt.Errorf("delete bucket: %s", err) - } - } - return nil - }) - if err != nil { - return err - } - - // Remove cached copy. - delete(b.buckets, string(key)) - - // Release all bucket pages to freelist. - child.nodes = nil - child.rootNode = nil - child.free() - - // Delete the node if we have a matching key. - c.node().del(key) - - return nil -} - -// Get retrieves the value for a key in the bucket. -// Returns a nil value if the key does not exist or if the key is a nested bucket. -// The returned value is only valid for the life of the transaction. -func (b *Bucket) Get(key []byte) []byte { - k, v, flags := b.Cursor().seek(key) - - // Return nil if this is a bucket. - if (flags & bucketLeafFlag) != 0 { - return nil - } - - // If our target node isn't the same key as what's passed in then return nil. - if !bytes.Equal(key, k) { - return nil - } - return v -} - -// Put sets the value for a key in the bucket. -// If the key exist then its previous value will be overwritten. -// Supplied value must remain valid for the life of the transaction. -// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large. -func (b *Bucket) Put(key []byte, value []byte) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } else if len(key) == 0 { - return ErrKeyRequired - } else if len(key) > MaxKeySize { - return ErrKeyTooLarge - } else if int64(len(value)) > MaxValueSize { - return ErrValueTooLarge - } - - // Move cursor to correct position. - c := b.Cursor() - k, _, flags := c.seek(key) - - // Return an error if there is an existing key with a bucket value. - if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 { - return ErrIncompatibleValue - } - - // Insert into node. - key = cloneBytes(key) - c.node().put(key, key, value, 0, 0) - - return nil -} - -// Delete removes a key from the bucket. -// If the key does not exist then nothing is done and a nil error is returned. -// Returns an error if the bucket was created from a read-only transaction. -func (b *Bucket) Delete(key []byte) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } - - // Move cursor to correct position. - c := b.Cursor() - k, _, flags := c.seek(key) - - // Return nil if the key doesn't exist. - if !bytes.Equal(key, k) { - return nil - } - - // Return an error if there is already existing bucket value. - if (flags & bucketLeafFlag) != 0 { - return ErrIncompatibleValue - } - - // Delete the node if we have a matching key. - c.node().del(key) - - return nil -} - -// Sequence returns the current integer for the bucket without incrementing it. -func (b *Bucket) Sequence() uint64 { return b.bucket.sequence } - -// SetSequence updates the sequence number for the bucket. -func (b *Bucket) SetSequence(v uint64) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } - - // Materialize the root node if it hasn't been already so that the - // bucket will be saved during commit. - if b.rootNode == nil { - _ = b.node(b.root, nil) - } - - // Increment and return the sequence. - b.bucket.sequence = v - return nil -} - -// NextSequence returns an autoincrementing integer for the bucket. -func (b *Bucket) NextSequence() (uint64, error) { - if b.tx.db == nil { - return 0, ErrTxClosed - } else if !b.Writable() { - return 0, ErrTxNotWritable - } - - // Materialize the root node if it hasn't been already so that the - // bucket will be saved during commit. - if b.rootNode == nil { - _ = b.node(b.root, nil) - } - - // Increment and return the sequence. - b.bucket.sequence++ - return b.bucket.sequence, nil -} - -// ForEach executes a function for each key/value pair in a bucket. -// If the provided function returns an error then the iteration is stopped and -// the error is returned to the caller. The provided function must not modify -// the bucket; this will result in undefined behavior. -func (b *Bucket) ForEach(fn func(k, v []byte) error) error { - if b.tx.db == nil { - return ErrTxClosed - } - c := b.Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - if err := fn(k, v); err != nil { - return err - } - } - return nil -} - -// Stat returns stats on a bucket. -func (b *Bucket) Stats() BucketStats { - var s, subStats BucketStats - pageSize := b.tx.db.pageSize - s.BucketN += 1 - if b.root == 0 { - s.InlineBucketN += 1 - } - b.forEachPage(func(p *page, depth int) { - if (p.flags & leafPageFlag) != 0 { - s.KeyN += int(p.count) - - // used totals the used bytes for the page - used := pageHeaderSize - - if p.count != 0 { - // If page has any elements, add all element headers. - used += leafPageElementSize * int(p.count-1) - - // Add all element key, value sizes. - // The computation takes advantage of the fact that the position - // of the last element's key/value equals to the total of the sizes - // of all previous elements' keys and values. - // It also includes the last element's header. - lastElement := p.leafPageElement(p.count - 1) - used += int(lastElement.pos + lastElement.ksize + lastElement.vsize) - } - - if b.root == 0 { - // For inlined bucket just update the inline stats - s.InlineBucketInuse += used - } else { - // For non-inlined bucket update all the leaf stats - s.LeafPageN++ - s.LeafInuse += used - s.LeafOverflowN += int(p.overflow) - - // Collect stats from sub-buckets. - // Do that by iterating over all element headers - // looking for the ones with the bucketLeafFlag. - for i := uint16(0); i < p.count; i++ { - e := p.leafPageElement(i) - if (e.flags & bucketLeafFlag) != 0 { - // For any bucket element, open the element value - // and recursively call Stats on the contained bucket. - subStats.Add(b.openBucket(e.value()).Stats()) - } - } - } - } else if (p.flags & branchPageFlag) != 0 { - s.BranchPageN++ - lastElement := p.branchPageElement(p.count - 1) - - // used totals the used bytes for the page - // Add header and all element headers. - used := pageHeaderSize + (branchPageElementSize * int(p.count-1)) - - // Add size of all keys and values. - // Again, use the fact that last element's position equals to - // the total of key, value sizes of all previous elements. - used += int(lastElement.pos + lastElement.ksize) - s.BranchInuse += used - s.BranchOverflowN += int(p.overflow) - } - - // Keep track of maximum page depth. - if depth+1 > s.Depth { - s.Depth = (depth + 1) - } - }) - - // Alloc stats can be computed from page counts and pageSize. - s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize - s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize - - // Add the max depth of sub-buckets to get total nested depth. - s.Depth += subStats.Depth - // Add the stats for all sub-buckets - s.Add(subStats) - return s -} - -// forEachPage iterates over every page in a bucket, including inline pages. -func (b *Bucket) forEachPage(fn func(*page, int)) { - // If we have an inline page then just use that. - if b.page != nil { - fn(b.page, 0) - return - } - - // Otherwise traverse the page hierarchy. - b.tx.forEachPage(b.root, 0, fn) -} - -// forEachPageNode iterates over every page (or node) in a bucket. -// This also includes inline pages. -func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) { - // If we have an inline page or root node then just use that. - if b.page != nil { - fn(b.page, nil, 0) - return - } - b._forEachPageNode(b.root, 0, fn) -} - -func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) { - var p, n = b.pageNode(pgid) - - // Execute function. - fn(p, n, depth) - - // Recursively loop over children. - if p != nil { - if (p.flags & branchPageFlag) != 0 { - for i := 0; i < int(p.count); i++ { - elem := p.branchPageElement(uint16(i)) - b._forEachPageNode(elem.pgid, depth+1, fn) - } - } - } else { - if !n.isLeaf { - for _, inode := range n.inodes { - b._forEachPageNode(inode.pgid, depth+1, fn) - } - } - } -} - -// spill writes all the nodes for this bucket to dirty pages. -func (b *Bucket) spill() error { - // Spill all child buckets first. - for name, child := range b.buckets { - // If the child bucket is small enough and it has no child buckets then - // write it inline into the parent bucket's page. Otherwise spill it - // like a normal bucket and make the parent value a pointer to the page. - var value []byte - if child.inlineable() { - child.free() - value = child.write() - } else { - if err := child.spill(); err != nil { - return err - } - - // Update the child bucket header in this bucket. - value = make([]byte, unsafe.Sizeof(bucket{})) - var bucket = (*bucket)(unsafe.Pointer(&value[0])) - *bucket = *child.bucket - } - - // Skip writing the bucket if there are no materialized nodes. - if child.rootNode == nil { - continue - } - - // Update parent node. - var c = b.Cursor() - k, _, flags := c.seek([]byte(name)) - if !bytes.Equal([]byte(name), k) { - panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k)) - } - if flags&bucketLeafFlag == 0 { - panic(fmt.Sprintf("unexpected bucket header flag: %x", flags)) - } - c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag) - } - - // Ignore if there's not a materialized root node. - if b.rootNode == nil { - return nil - } - - // Spill nodes. - if err := b.rootNode.spill(); err != nil { - return err - } - b.rootNode = b.rootNode.root() - - // Update the root node for this bucket. - if b.rootNode.pgid >= b.tx.meta.pgid { - panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid)) - } - b.root = b.rootNode.pgid - - return nil -} - -// inlineable returns true if a bucket is small enough to be written inline -// and if it contains no subbuckets. Otherwise returns false. -func (b *Bucket) inlineable() bool { - var n = b.rootNode - - // Bucket must only contain a single leaf node. - if n == nil || !n.isLeaf { - return false - } - - // Bucket is not inlineable if it contains subbuckets or if it goes beyond - // our threshold for inline bucket size. - var size = pageHeaderSize - for _, inode := range n.inodes { - size += leafPageElementSize + len(inode.key) + len(inode.value) - - if inode.flags&bucketLeafFlag != 0 { - return false - } else if size > b.maxInlineBucketSize() { - return false - } - } - - return true -} - -// Returns the maximum total size of a bucket to make it a candidate for inlining. -func (b *Bucket) maxInlineBucketSize() int { - return b.tx.db.pageSize / 4 -} - -// write allocates and writes a bucket to a byte slice. -func (b *Bucket) write() []byte { - // Allocate the appropriate size. - var n = b.rootNode - var value = make([]byte, bucketHeaderSize+n.size()) - - // Write a bucket header. - var bucket = (*bucket)(unsafe.Pointer(&value[0])) - *bucket = *b.bucket - - // Convert byte slice to a fake page and write the root node. - var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) - n.write(p) - - return value -} - -// rebalance attempts to balance all nodes. -func (b *Bucket) rebalance() { - for _, n := range b.nodes { - n.rebalance() - } - for _, child := range b.buckets { - child.rebalance() - } -} - -// node creates a node from a page and associates it with a given parent. -func (b *Bucket) node(pgid pgid, parent *node) *node { - _assert(b.nodes != nil, "nodes map expected") - - // Retrieve node if it's already been created. - if n := b.nodes[pgid]; n != nil { - return n - } - - // Otherwise create a node and cache it. - n := &node{bucket: b, parent: parent} - if parent == nil { - b.rootNode = n - } else { - parent.children = append(parent.children, n) - } - - // Use the inline page if this is an inline bucket. - var p = b.page - if p == nil { - p = b.tx.page(pgid) - } - - // Read the page into the node and cache it. - n.read(p) - b.nodes[pgid] = n - - // Update statistics. - b.tx.stats.NodeCount++ - - return n -} - -// free recursively frees all pages in the bucket. -func (b *Bucket) free() { - if b.root == 0 { - return - } - - var tx = b.tx - b.forEachPageNode(func(p *page, n *node, _ int) { - if p != nil { - tx.db.freelist.free(tx.meta.txid, p) - } else { - n.free() - } - }) - b.root = 0 -} - -// dereference removes all references to the old mmap. -func (b *Bucket) dereference() { - if b.rootNode != nil { - b.rootNode.root().dereference() - } - - for _, child := range b.buckets { - child.dereference() - } -} - -// pageNode returns the in-memory node, if it exists. -// Otherwise returns the underlying page. -func (b *Bucket) pageNode(id pgid) (*page, *node) { - // Inline buckets have a fake page embedded in their value so treat them - // differently. We'll return the rootNode (if available) or the fake page. - if b.root == 0 { - if id != 0 { - panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id)) - } - if b.rootNode != nil { - return nil, b.rootNode - } - return b.page, nil - } - - // Check the node cache for non-inline buckets. - if b.nodes != nil { - if n := b.nodes[id]; n != nil { - return nil, n - } - } - - // Finally lookup the page from the transaction if no node is materialized. - return b.tx.page(id), nil -} - -// BucketStats records statistics about resources used by a bucket. -type BucketStats struct { - // Page count statistics. - BranchPageN int // number of logical branch pages - BranchOverflowN int // number of physical branch overflow pages - LeafPageN int // number of logical leaf pages - LeafOverflowN int // number of physical leaf overflow pages - - // Tree statistics. - KeyN int // number of keys/value pairs - Depth int // number of levels in B+tree - - // Page size utilization. - BranchAlloc int // bytes allocated for physical branch pages - BranchInuse int // bytes actually used for branch data - LeafAlloc int // bytes allocated for physical leaf pages - LeafInuse int // bytes actually used for leaf data - - // Bucket statistics - BucketN int // total number of buckets including the top bucket - InlineBucketN int // total number on inlined buckets - InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse) -} - -func (s *BucketStats) Add(other BucketStats) { - s.BranchPageN += other.BranchPageN - s.BranchOverflowN += other.BranchOverflowN - s.LeafPageN += other.LeafPageN - s.LeafOverflowN += other.LeafOverflowN - s.KeyN += other.KeyN - if s.Depth < other.Depth { - s.Depth = other.Depth - } - s.BranchAlloc += other.BranchAlloc - s.BranchInuse += other.BranchInuse - s.LeafAlloc += other.LeafAlloc - s.LeafInuse += other.LeafInuse - - s.BucketN += other.BucketN - s.InlineBucketN += other.InlineBucketN - s.InlineBucketInuse += other.InlineBucketInuse -} - -// cloneBytes returns a copy of a given slice. -func cloneBytes(v []byte) []byte { - var clone = make([]byte, len(v)) - copy(clone, v) - return clone -} diff --git a/vendor/github.com/coreos/bbolt/bucket_test.go b/vendor/github.com/coreos/bbolt/bucket_test.go deleted file mode 100644 index b7ce32c..0000000 --- a/vendor/github.com/coreos/bbolt/bucket_test.go +++ /dev/null @@ -1,1959 +0,0 @@ -package bolt_test - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "log" - "math/rand" - "os" - "strconv" - "strings" - "testing" - "testing/quick" - - "github.com/coreos/bbolt" -) - -// Ensure that a bucket that gets a non-existent key returns nil. -func TestBucket_Get_NonExistent(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); v != nil { - t.Fatal("expected nil value") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can read a value that is not flushed yet. -func TestBucket_Get_FromNode(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); !bytes.Equal(v, []byte("bar")) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket retrieved via Get() returns a nil. -func TestBucket_Get_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - - if tx.Bucket([]byte("widgets")).Get([]byte("foo")) != nil { - t.Fatal("expected nil value") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a slice returned from a bucket has a capacity equal to its length. -// This also allows slices to be appended to since it will require a realloc by Go. -// -// https://github.com/boltdb/bolt/issues/544 -func TestBucket_Get_Capacity(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Write key to a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("bucket")) - if err != nil { - return err - } - return b.Put([]byte("key"), []byte("val")) - }); err != nil { - t.Fatal(err) - } - - // Retrieve value and attempt to append to it. - if err := db.Update(func(tx *bolt.Tx) error { - k, v := tx.Bucket([]byte("bucket")).Cursor().First() - - // Verify capacity. - if len(k) != cap(k) { - t.Fatalf("unexpected key slice capacity: %d", cap(k)) - } else if len(v) != cap(v) { - t.Fatalf("unexpected value slice capacity: %d", cap(v)) - } - - // Ensure slice can be appended to without a segfault. - k = append(k, []byte("123")...) - v = append(v, []byte("123")...) - _, _ = k, v // to pass ineffassign - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can write a key/value. -func TestBucket_Put(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - v := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - if !bytes.Equal([]byte("bar"), v) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can rewrite a key in the same transaction. -func TestBucket_Put_Repeat(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("baz")); err != nil { - t.Fatal(err) - } - - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - if !bytes.Equal([]byte("baz"), value) { - t.Fatalf("unexpected value: %v", value) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can write a bunch of large values. -func TestBucket_Put_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - count, factor := 100, 200 - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for i := 1; i < count; i++ { - if err := b.Put([]byte(strings.Repeat("0", i*factor)), []byte(strings.Repeat("X", (count-i)*factor))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 1; i < count; i++ { - value := b.Get([]byte(strings.Repeat("0", i*factor))) - if !bytes.Equal(value, []byte(strings.Repeat("X", (count-i)*factor))) { - t.Fatalf("unexpected value: %v", value) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a database can perform multiple large appends safely. -func TestDB_Put_VeryLarge(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - n, batchN := 400000, 200000 - ksize, vsize := 8, 500 - - db := MustOpenDB() - defer db.MustClose() - - for i := 0; i < n; i += batchN { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for j := 0; j < batchN; j++ { - k, v := make([]byte, ksize), make([]byte, vsize) - binary.BigEndian.PutUint32(k, uint32(i+j)) - if err := b.Put(k, v); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - } -} - -// Ensure that a setting a value on a key with a bucket value returns an error. -func TestBucket_Put_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b0, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if err := b0.Put([]byte("foo"), []byte("bar")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a setting a value while the transaction is closed returns an error. -func TestBucket_Put_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that setting a value on a read-only bucket returns an error. -func TestBucket_Put_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can delete an existing key. -func TestBucket_Delete(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); v != nil { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a large set of keys will work correctly. -func TestBucket_Delete_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < 100; i++ { - if err := b.Put([]byte(strconv.Itoa(i)), []byte(strings.Repeat("*", 1024))); err != nil { - t.Fatal(err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < 100; i++ { - if err := b.Delete([]byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < 100; i++ { - if v := b.Get([]byte(strconv.Itoa(i))); v != nil { - t.Fatalf("unexpected value: %v, i=%d", v, i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Deleting a very large list of keys will cause the freelist to use overflow. -func TestBucket_Delete_FreelistOverflow(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - db := MustOpenDB() - defer db.MustClose() - - k := make([]byte, 16) - for i := uint64(0); i < 10000; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("0")) - if err != nil { - t.Fatalf("bucket error: %s", err) - } - - for j := uint64(0); j < 1000; j++ { - binary.BigEndian.PutUint64(k[:8], i) - binary.BigEndian.PutUint64(k[8:], j) - if err := b.Put(k, nil); err != nil { - t.Fatalf("put error: %s", err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - } - - // Delete all of them in one large transaction - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("0")) - c := b.Cursor() - for k, _ := c.First(); k != nil; k, _ = c.Next() { - if err := c.Delete(); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Check more than an overflow's worth of pages are freed. - stats := db.Stats() - freePages := stats.FreePageN + stats.PendingPageN - if freePages <= 0xFFFF { - t.Fatalf("expected more than 0xFFFF free pages, got %v", freePages) - } - - // Free page count should be preserved on reopen. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - db.MustReopen() - if reopenFreePages := db.Stats().FreePageN; freePages != reopenFreePages { - t.Fatalf("expected %d free pages, got %+v", freePages, db.Stats()) - } -} - -// Ensure that deleting of non-existing key is a no-op. -func TestBucket_Delete_NonExisting(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if _, err = b.CreateBucket([]byte("nested")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - if err := b.Delete([]byte("foo")); err != nil { - t.Fatal(err) - } - if b.Bucket([]byte("nested")) == nil { - t.Fatal("nested bucket has been deleted") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that accessing and updating nested buckets is ok across transactions. -func TestBucket_Nested(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - // Create a widgets bucket. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - // Create a widgets/foo bucket. - _, err = b.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - // Create a widgets/bar key. - if err := b.Put([]byte("bar"), []byte("0000")); err != nil { - t.Fatal(err) - } - - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Update widgets/bar. - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - if err := b.Put([]byte("bar"), []byte("xxxx")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Cause a split. - if err := db.Update(func(tx *bolt.Tx) error { - var b = tx.Bucket([]byte("widgets")) - for i := 0; i < 10000; i++ { - if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Insert into widgets/foo/baz. - if err := db.Update(func(tx *bolt.Tx) error { - var b = tx.Bucket([]byte("widgets")) - if err := b.Bucket([]byte("foo")).Put([]byte("baz"), []byte("yyyy")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Verify. - if err := db.View(func(tx *bolt.Tx) error { - var b = tx.Bucket([]byte("widgets")) - if v := b.Bucket([]byte("foo")).Get([]byte("baz")); !bytes.Equal(v, []byte("yyyy")) { - t.Fatalf("unexpected value: %v", v) - } - if v := b.Get([]byte("bar")); !bytes.Equal(v, []byte("xxxx")) { - t.Fatalf("unexpected value: %v", v) - } - for i := 0; i < 10000; i++ { - if v := b.Get([]byte(strconv.Itoa(i))); !bytes.Equal(v, []byte(strconv.Itoa(i))) { - t.Fatalf("unexpected value: %v", v) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket using Delete() returns an error. -func TestBucket_Delete_Bucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a key on a read-only bucket returns an error. -func TestBucket_Delete_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).Delete([]byte("foo")); err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a deleting value while the transaction is closed returns an error. -func TestBucket_Delete_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that deleting a bucket causes nested buckets to be deleted. -func TestBucket_DeleteBucket_Nested(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - foo, err := widgets.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - bar, err := foo.CreateBucket([]byte("bar")) - if err != nil { - t.Fatal(err) - } - if err := bar.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket causes nested buckets to be deleted after they have been committed. -func TestBucket_DeleteBucket_Nested2(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - foo, err := widgets.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - bar, err := foo.CreateBucket([]byte("bar")) - if err != nil { - t.Fatal(err) - } - - if err := bar.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - widgets := tx.Bucket([]byte("widgets")) - if widgets == nil { - t.Fatal("expected widgets bucket") - } - - foo := widgets.Bucket([]byte("foo")) - if foo == nil { - t.Fatal("expected foo bucket") - } - - bar := foo.Bucket([]byte("bar")) - if bar == nil { - t.Fatal("expected bar bucket") - } - - if v := bar.Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) { - t.Fatalf("unexpected value: %v", v) - } - if err := tx.DeleteBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) != nil { - t.Fatal("expected bucket to be deleted") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a child bucket with multiple pages causes all pages to get collected. -// NOTE: Consistency check in bolt_test.DB.Close() will panic if pages not freed properly. -func TestBucket_DeleteBucket_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - foo, err := widgets.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < 1000; i++ { - if err := foo.Put([]byte(fmt.Sprintf("%d", i)), []byte(fmt.Sprintf("%0100d", i))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a simple value retrieved via Bucket() returns a nil. -func TestBucket_Bucket_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if b := tx.Bucket([]byte("widgets")).Bucket([]byte("foo")); b != nil { - t.Fatal("expected nil bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that creating a bucket on an existing non-bucket key returns an error. -func TestBucket_CreateBucket_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if _, err := widgets.CreateBucket([]byte("foo")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket on an existing non-bucket key returns an error. -func TestBucket_DeleteBucket_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure bucket can set and update its sequence number. -func TestBucket_Sequence(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - bkt, err := tx.CreateBucket([]byte("0")) - if err != nil { - t.Fatal(err) - } - - // Retrieve sequence. - if v := bkt.Sequence(); v != 0 { - t.Fatalf("unexpected sequence: %d", v) - } - - // Update sequence. - if err := bkt.SetSequence(1000); err != nil { - t.Fatal(err) - } - - // Read sequence again. - if v := bkt.Sequence(); v != 1000 { - t.Fatalf("unexpected sequence: %d", v) - } - - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify sequence in separate transaction. - if err := db.View(func(tx *bolt.Tx) error { - if v := tx.Bucket([]byte("0")).Sequence(); v != 1000 { - t.Fatalf("unexpected sequence: %d", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can return an autoincrementing sequence. -func TestBucket_NextSequence(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - woojits, err := tx.CreateBucket([]byte("woojits")) - if err != nil { - t.Fatal(err) - } - - // Make sure sequence increments. - if seq, err := widgets.NextSequence(); err != nil { - t.Fatal(err) - } else if seq != 1 { - t.Fatalf("unexpecte sequence: %d", seq) - } - - if seq, err := widgets.NextSequence(); err != nil { - t.Fatal(err) - } else if seq != 2 { - t.Fatalf("unexpected sequence: %d", seq) - } - - // Buckets should be separate. - if seq, err := woojits.NextSequence(); err != nil { - t.Fatal(err) - } else if seq != 1 { - t.Fatalf("unexpected sequence: %d", 1) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket will persist an autoincrementing sequence even if its -// the only thing updated on the bucket. -// https://github.com/boltdb/bolt/issues/296 -func TestBucket_NextSequence_Persist(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.Bucket([]byte("widgets")).NextSequence(); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - seq, err := tx.Bucket([]byte("widgets")).NextSequence() - if err != nil { - t.Fatalf("unexpected error: %s", err) - } else if seq != 2 { - t.Fatalf("unexpected sequence: %d", seq) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that retrieving the next sequence on a read-only bucket returns an error. -func TestBucket_NextSequence_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - _, err := tx.Bucket([]byte("widgets")).NextSequence() - if err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that retrieving the next sequence for a bucket on a closed database return an error. -func TestBucket_NextSequence_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - if _, err := b.NextSequence(); err != bolt.ErrTxClosed { - t.Fatal(err) - } -} - -// Ensure a user can loop over all key/value pairs in a bucket. -func TestBucket_ForEach(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("0000")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("0001")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte("0002")); err != nil { - t.Fatal(err) - } - - var index int - if err := b.ForEach(func(k, v []byte) error { - switch index { - case 0: - if !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0002")) { - t.Fatalf("unexpected value: %v", v) - } - case 1: - if !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0001")) { - t.Fatalf("unexpected value: %v", v) - } - case 2: - if !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0000")) { - t.Fatalf("unexpected value: %v", v) - } - } - index++ - return nil - }); err != nil { - t.Fatal(err) - } - - if index != 3 { - t.Fatalf("unexpected index: %d", index) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a database can stop iteration early. -func TestBucket_ForEach_ShortCircuit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte("0000")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("0000")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("0000")); err != nil { - t.Fatal(err) - } - - var index int - if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error { - index++ - if bytes.Equal(k, []byte("baz")) { - return errors.New("marker") - } - return nil - }); err == nil || err.Error() != "marker" { - t.Fatalf("unexpected error: %s", err) - } - if index != 2 { - t.Fatalf("unexpected index: %d", index) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that looping over a bucket on a closed database returns an error. -func TestBucket_ForEach_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - if err := b.ForEach(func(k, v []byte) error { return nil }); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that an error is returned when inserting with an empty key. -func TestBucket_Put_EmptyKey(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte(""), []byte("bar")); err != bolt.ErrKeyRequired { - t.Fatalf("unexpected error: %s", err) - } - if err := b.Put(nil, []byte("bar")); err != bolt.ErrKeyRequired { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that an error is returned when inserting with a key that's too large. -func TestBucket_Put_KeyTooLarge(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put(make([]byte, 32769), []byte("bar")); err != bolt.ErrKeyTooLarge { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that an error is returned when inserting a value that's too large. -func TestBucket_Put_ValueTooLarge(t *testing.T) { - // Skip this test on DroneCI because the machine is resource constrained. - if os.Getenv("DRONE") == "true" { - t.Skip("not enough RAM for test") - } - - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), make([]byte, bolt.MaxValueSize+1)); err != bolt.ErrValueTooLarge { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket can calculate stats. -func TestBucket_Stats(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Add bucket with fewer keys but one big value. - bigKey := []byte("really-big-value") - for i := 0; i < 500; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("woojits")) - if err != nil { - t.Fatal(err) - } - - if err := b.Put([]byte(fmt.Sprintf("%03d", i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - } - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("woojits")).Put(bigKey, []byte(strings.Repeat("*", 10000))); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("woojits")).Stats() - if stats.BranchPageN != 1 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 7 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 2 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 501 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 2 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } - - branchInuse := 16 // branch page header - branchInuse += 7 * 16 // branch elements - branchInuse += 7 * 3 // branch keys (6 3-byte keys) - if stats.BranchInuse != branchInuse { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } - - leafInuse := 7 * 16 // leaf page header - leafInuse += 501 * 16 // leaf elements - leafInuse += 500*3 + len(bigKey) // leaf keys - leafInuse += 1*10 + 2*90 + 3*400 + 10000 // leaf values - if stats.LeafInuse != leafInuse { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - // Only check allocations for 4KB pages. - if db.Info().PageSize == 4096 { - if stats.BranchAlloc != 4096 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 36864 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 0 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 0 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket with random insertion utilizes fill percentage correctly. -func TestBucket_Stats_RandomFill(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } else if os.Getpagesize() != 4096 { - t.Skip("invalid page size for test") - } - - db := MustOpenDB() - defer db.MustClose() - - // Add a set of values in random order. It will be the same random - // order so we can maintain consistency between test runs. - var count int - rand := rand.New(rand.NewSource(42)) - for _, i := range rand.Perm(1000) { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("woojits")) - if err != nil { - t.Fatal(err) - } - b.FillPercent = 0.9 - for _, j := range rand.Perm(100) { - index := (j * 10000) + i - if err := b.Put([]byte(fmt.Sprintf("%d000000000000000", index)), []byte("0000000000")); err != nil { - t.Fatal(err) - } - count++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("woojits")).Stats() - if stats.KeyN != 100000 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } - - if stats.BranchPageN != 98 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.BranchInuse != 130984 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.BranchAlloc != 401408 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } - - if stats.LeafPageN != 3412 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.LeafInuse != 4742482 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } else if stats.LeafAlloc != 13975552 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket can calculate stats. -func TestBucket_Stats_Small(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - // Add a bucket that fits on a single root leaf. - b, err := tx.CreateBucket([]byte("whozawhats")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("whozawhats")) - stats := b.Stats() - if stats.BranchPageN != 0 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 0 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 1 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 1 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 0 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.LeafInuse != 0 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if db.Info().PageSize == 4096 { - if stats.BranchAlloc != 0 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 0 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 1 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 16+16+6 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestBucket_Stats_EmptyBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - // Add a bucket that fits on a single root leaf. - if _, err := tx.CreateBucket([]byte("whozawhats")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("whozawhats")) - stats := b.Stats() - if stats.BranchPageN != 0 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 0 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 0 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 1 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 0 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.LeafInuse != 0 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if db.Info().PageSize == 4096 { - if stats.BranchAlloc != 0 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 0 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 1 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 16 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket can calculate stats. -func TestBucket_Stats_Nested(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 100; i++ { - if err := b.Put([]byte(fmt.Sprintf("%02d", i)), []byte(fmt.Sprintf("%02d", i))); err != nil { - t.Fatal(err) - } - } - - bar, err := b.CreateBucket([]byte("bar")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 10; i++ { - if err := bar.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - - baz, err := bar.CreateBucket([]byte("baz")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 10; i++ { - if err := baz.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("foo")) - stats := b.Stats() - if stats.BranchPageN != 0 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 2 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 122 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 3 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 0 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } - - foo := 16 // foo (pghdr) - foo += 101 * 16 // foo leaf elements - foo += 100*2 + 100*2 // foo leaf key/values - foo += 3 + 16 // foo -> bar key/value - - bar := 16 // bar (pghdr) - bar += 11 * 16 // bar leaf elements - bar += 10 + 10 // bar leaf key/values - bar += 3 + 16 // bar -> baz key/value - - baz := 16 // baz (inline) (pghdr) - baz += 10 * 16 // baz leaf elements - baz += 10 + 10 // baz leaf key/values - - if stats.LeafInuse != foo+bar+baz { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if db.Info().PageSize == 4096 { - if stats.BranchAlloc != 0 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 8192 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 3 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 1 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != baz { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a large bucket can calculate stats. -func TestBucket_Stats_Large(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - db := MustOpenDB() - defer db.MustClose() - - var index int - for i := 0; i < 100; i++ { - // Add bucket with lots of keys. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 1000; i++ { - if err := b.Put([]byte(strconv.Itoa(index)), []byte(strconv.Itoa(index))); err != nil { - t.Fatal(err) - } - index++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("widgets")).Stats() - if stats.BranchPageN != 13 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 1196 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 100000 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 3 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 25257 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.LeafInuse != 2596916 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if db.Info().PageSize == 4096 { - if stats.BranchAlloc != 53248 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 4898816 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 0 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 0 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can write random keys and values across multiple transactions. -func TestBucket_Put_Single(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - index := 0 - if err := quick.Check(func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - m := make(map[string][]byte) - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - for _, item := range items { - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).Put(item.Key, item.Value); err != nil { - panic("put error: " + err.Error()) - } - m[string(item.Key)] = item.Value - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify all key/values so far. - if err := db.View(func(tx *bolt.Tx) error { - i := 0 - for k, v := range m { - value := tx.Bucket([]byte("widgets")).Get([]byte(k)) - if !bytes.Equal(value, v) { - t.Logf("value mismatch [run %d] (%d of %d):\nkey: %x\ngot: %x\nexp: %x", index, i, len(m), []byte(k), value, v) - db.CopyTempFile() - t.FailNow() - } - i++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - index++ - return true - }, qconfig()); err != nil { - t.Error(err) - } -} - -// Ensure that a transaction can insert multiple key/value pairs at once. -func TestBucket_Put_Multiple(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - if err := quick.Check(func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify all items exist. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for _, item := range items { - value := b.Get(item.Key) - if !bytes.Equal(item.Value, value) { - db.CopyTempFile() - t.Fatalf("exp=%x; got=%x", item.Value, value) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - return true - }, qconfig()); err != nil { - t.Error(err) - } -} - -// Ensure that a transaction can delete all key/value pairs and return to a single leaf page. -func TestBucket_Delete_Quick(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - if err := quick.Check(func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Remove items one at a time and check consistency. - for _, item := range items { - if err := db.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Delete(item.Key) - }); err != nil { - t.Fatal(err) - } - } - - // Anything before our deletion index should be nil. - if err := db.View(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error { - t.Fatalf("bucket should be empty; found: %06x", trunc(k, 3)) - return nil - }); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - return true - }, qconfig()); err != nil { - t.Error(err) - } -} - -func ExampleBucket_Put() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a bucket. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - - // Set the value "bar" for the key "foo". - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Read value back in a different read-only transaction. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value of 'foo' is: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value of 'foo' is: bar -} - -func ExampleBucket_Delete() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a bucket. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - - // Set the value "bar" for the key "foo". - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - - // Retrieve the key back from the database and verify it. - value := b.Get([]byte("foo")) - fmt.Printf("The value of 'foo' was: %s\n", value) - - return nil - }); err != nil { - log.Fatal(err) - } - - // Delete the key in a different write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Delete([]byte("foo")) - }); err != nil { - log.Fatal(err) - } - - // Retrieve the key again. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - if value == nil { - fmt.Printf("The value of 'foo' is now: nil\n") - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value of 'foo' was: bar - // The value of 'foo' is now: nil -} - -func ExampleBucket_ForEach() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Insert data into a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("animals")) - if err != nil { - return err - } - - if err := b.Put([]byte("dog"), []byte("fun")); err != nil { - return err - } - if err := b.Put([]byte("cat"), []byte("lame")); err != nil { - return err - } - if err := b.Put([]byte("liger"), []byte("awesome")); err != nil { - return err - } - - // Iterate over items in sorted key order. - if err := b.ForEach(func(k, v []byte) error { - fmt.Printf("A %s is %s.\n", k, v) - return nil - }); err != nil { - return err - } - - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // A cat is lame. - // A dog is fun. - // A liger is awesome. -} diff --git a/vendor/github.com/coreos/bbolt/cmd/bolt/main.go b/vendor/github.com/coreos/bbolt/cmd/bolt/main.go deleted file mode 100644 index eb85e05..0000000 --- a/vendor/github.com/coreos/bbolt/cmd/bolt/main.go +++ /dev/null @@ -1,2136 +0,0 @@ -package main - -import ( - "bytes" - "encoding/binary" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "math/rand" - "os" - "runtime" - "runtime/pprof" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf8" - "unsafe" - - bolt "github.com/coreos/bbolt" -) - -var ( - // ErrUsage is returned when a usage message was printed and the process - // should simply exit with an error. - ErrUsage = errors.New("usage") - - // ErrUnknownCommand is returned when a CLI command is not specified. - ErrUnknownCommand = errors.New("unknown command") - - // ErrPathRequired is returned when the path to a Bolt database is not specified. - ErrPathRequired = errors.New("path required") - - // ErrFileNotFound is returned when a Bolt database does not exist. - ErrFileNotFound = errors.New("file not found") - - // ErrInvalidValue is returned when a benchmark reads an unexpected value. - ErrInvalidValue = errors.New("invalid value") - - // ErrCorrupt is returned when a checking a data file finds errors. - ErrCorrupt = errors.New("invalid value") - - // ErrNonDivisibleBatchSize is returned when the batch size can't be evenly - // divided by the iteration count. - ErrNonDivisibleBatchSize = errors.New("number of iterations must be divisible by the batch size") - - // ErrPageIDRequired is returned when a required page id is not specified. - ErrPageIDRequired = errors.New("page id required") - - // ErrBucketRequired is returned when a bucket is not specified. - ErrBucketRequired = errors.New("bucket required") - - // ErrBucketNotFound is returned when a bucket is not found. - ErrBucketNotFound = errors.New("bucket not found") - - // ErrKeyRequired is returned when a key is not specified. - ErrKeyRequired = errors.New("key required") - - // ErrKeyNotFound is returned when a key is not found. - ErrKeyNotFound = errors.New("key not found") -) - -// PageHeaderSize represents the size of the bolt.page header. -const PageHeaderSize = 16 - -func main() { - m := NewMain() - if err := m.Run(os.Args[1:]...); err == ErrUsage { - os.Exit(2) - } else if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } -} - -// Main represents the main program execution. -type Main struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewMain returns a new instance of Main connect to the standard input/output. -func NewMain() *Main { - return &Main{ - Stdin: os.Stdin, - Stdout: os.Stdout, - Stderr: os.Stderr, - } -} - -// Run executes the program. -func (m *Main) Run(args ...string) error { - // Require a command at the beginning. - if len(args) == 0 || strings.HasPrefix(args[0], "-") { - fmt.Fprintln(m.Stderr, m.Usage()) - return ErrUsage - } - - // Execute command. - switch args[0] { - case "help": - fmt.Fprintln(m.Stderr, m.Usage()) - return ErrUsage - case "bench": - return newBenchCommand(m).Run(args[1:]...) - case "buckets": - return newBucketsCommand(m).Run(args[1:]...) - case "check": - return newCheckCommand(m).Run(args[1:]...) - case "compact": - return newCompactCommand(m).Run(args[1:]...) - case "dump": - return newDumpCommand(m).Run(args[1:]...) - case "page-item": - return newPageItemCommand(m).Run(args[1:]...) - case "get": - return newGetCommand(m).Run(args[1:]...) - case "info": - return newInfoCommand(m).Run(args[1:]...) - case "keys": - return newKeysCommand(m).Run(args[1:]...) - case "page": - return newPageCommand(m).Run(args[1:]...) - case "pages": - return newPagesCommand(m).Run(args[1:]...) - case "stats": - return newStatsCommand(m).Run(args[1:]...) - default: - return ErrUnknownCommand - } -} - -// Usage returns the help message. -func (m *Main) Usage() string { - return strings.TrimLeft(` -Bolt is a tool for inspecting bolt databases. - -Usage: - - bolt command [arguments] - -The commands are: - - bench run synthetic benchmark against bolt - buckets print a list of buckets - check verifies integrity of bolt database - compact copies a bolt database, compacting it in the process - dump print a hexadecimal dump of a single page - get print the value of a key in a bucket - info print basic info - keys print a list of keys in a bucket - help print this screen - page print one or more pages in human readable format - pages print list of pages with their types - page-item print the key and value of a page item. - stats iterate over all pages and generate usage stats - -Use "bolt [command] -h" for more information about a command. -`, "\n") -} - -// CheckCommand represents the "check" command execution. -type CheckCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewCheckCommand returns a CheckCommand. -func newCheckCommand(m *Main) *CheckCommand { - return &CheckCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *CheckCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path. - path := fs.Arg(0) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Open database. - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return err - } - defer db.Close() - - // Perform consistency check. - return db.View(func(tx *bolt.Tx) error { - var count int - for err := range tx.Check() { - fmt.Fprintln(cmd.Stdout, err) - count++ - } - - // Print summary of errors. - if count > 0 { - fmt.Fprintf(cmd.Stdout, "%d errors found\n", count) - return ErrCorrupt - } - - // Notify user that database is valid. - fmt.Fprintln(cmd.Stdout, "OK") - return nil - }) -} - -// Usage returns the help message. -func (cmd *CheckCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt check PATH - -Check opens a database at PATH and runs an exhaustive check to verify that -all pages are accessible or are marked as freed. It also verifies that no -pages are double referenced. - -Verification errors will stream out as they are found and the process will -return after all pages have been checked. -`, "\n") -} - -// InfoCommand represents the "info" command execution. -type InfoCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewInfoCommand returns a InfoCommand. -func newInfoCommand(m *Main) *InfoCommand { - return &InfoCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *InfoCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path. - path := fs.Arg(0) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Open the database. - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return err - } - defer db.Close() - - // Print basic database info. - info := db.Info() - fmt.Fprintf(cmd.Stdout, "Page Size: %d\n", info.PageSize) - - return nil -} - -// Usage returns the help message. -func (cmd *InfoCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt info PATH - -Info prints basic information about the Bolt database at PATH. -`, "\n") -} - -// DumpCommand represents the "dump" command execution. -type DumpCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// newDumpCommand returns a DumpCommand. -func newDumpCommand(m *Main) *DumpCommand { - return &DumpCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *DumpCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path and page id. - path := fs.Arg(0) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Read page ids. - pageIDs, err := atois(fs.Args()[1:]) - if err != nil { - return err - } else if len(pageIDs) == 0 { - return ErrPageIDRequired - } - - // Open database to retrieve page size. - pageSize, err := ReadPageSize(path) - if err != nil { - return err - } - - // Open database file handler. - f, err := os.Open(path) - if err != nil { - return err - } - defer func() { _ = f.Close() }() - - // Print each page listed. - for i, pageID := range pageIDs { - // Print a separator. - if i > 0 { - fmt.Fprintln(cmd.Stdout, "===============================================") - } - - // Print page to stdout. - if err := cmd.PrintPage(cmd.Stdout, f, pageID, pageSize); err != nil { - return err - } - } - - return nil -} - -// PrintPage prints a given page as hexadecimal. -func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error { - const bytesPerLineN = 16 - - // Read page into buffer. - buf := make([]byte, pageSize) - addr := pageID * pageSize - if n, err := r.ReadAt(buf, int64(addr)); err != nil { - return err - } else if n != pageSize { - return io.ErrUnexpectedEOF - } - - // Write out to writer in 16-byte lines. - var prev []byte - var skipped bool - for offset := 0; offset < pageSize; offset += bytesPerLineN { - // Retrieve current 16-byte line. - line := buf[offset : offset+bytesPerLineN] - isLastLine := (offset == (pageSize - bytesPerLineN)) - - // If it's the same as the previous line then print a skip. - if bytes.Equal(line, prev) && !isLastLine { - if !skipped { - fmt.Fprintf(w, "%07x *\n", addr+offset) - skipped = true - } - } else { - // Print line as hexadecimal in 2-byte groups. - fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset, - line[0:2], line[2:4], line[4:6], line[6:8], - line[8:10], line[10:12], line[12:14], line[14:16], - ) - - skipped = false - } - - // Save the previous line. - prev = line - } - fmt.Fprint(w, "\n") - - return nil -} - -// Usage returns the help message. -func (cmd *DumpCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt dump PATH pageid [pageid...] - -Dump prints a hexadecimal dump of one or more pages. -`, "\n") -} - -// PageItemCommand represents the "page-item" command execution. -type PageItemCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// newPageItemCommand returns a PageItemCommand. -func newPageItemCommand(m *Main) *PageItemCommand { - return &PageItemCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -type pageItemOptions struct { - help bool - keyOnly bool - valueOnly bool - format string -} - -// Run executes the command. -func (cmd *PageItemCommand) Run(args ...string) error { - // Parse flags. - options := &pageItemOptions{} - fs := flag.NewFlagSet("", flag.ContinueOnError) - fs.BoolVar(&options.keyOnly, "key-only", false, "Print only the key") - fs.BoolVar(&options.valueOnly, "value-only", false, "Print only the value") - fs.StringVar(&options.format, "format", "ascii-encoded", "Output format. One of: ascii-encoded|hex|bytes") - fs.BoolVar(&options.help, "h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if options.help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - if options.keyOnly && options.valueOnly { - return fmt.Errorf("The --key-only or --value-only flag may be set, but not both.") - } - - // Require database path and page id. - path := fs.Arg(0) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Read page id. - pageID, err := strconv.Atoi(fs.Arg(1)) - if err != nil { - return err - } - - // Read item id. - itemID, err := strconv.Atoi(fs.Arg(2)) - if err != nil { - return err - } - - // Open database file handler. - f, err := os.Open(path) - if err != nil { - return err - } - defer func() { _ = f.Close() }() - - // Retrieve page info and page size. - _, buf, err := ReadPage(path, pageID) - if err != nil { - return err - } - - if !options.valueOnly { - err := cmd.PrintLeafItemKey(cmd.Stdout, buf, uint16(itemID), options.format) - if err != nil { - return err - } - } - if !options.keyOnly { - err := cmd.PrintLeafItemValue(cmd.Stdout, buf, uint16(itemID), options.format) - if err != nil { - return err - } - } - return nil -} - -// leafPageElement retrieves a leaf page element. -func (cmd *PageItemCommand) leafPageElement(pageBytes []byte, index uint16) (*leafPageElement, error) { - p := (*page)(unsafe.Pointer(&pageBytes[0])) - if index >= p.count { - return nil, fmt.Errorf("leafPageElement: expected item index less than %d, but got %d.", p.count, index) - } - if p.Type() != "leaf" { - return nil, fmt.Errorf("leafPageElement: expected page type of 'leaf', but got '%s'", p.Type()) - } - return p.leafPageElement(index), nil -} - -// writeBytes writes the byte to the writer. Supported formats: ascii-encoded, hex, bytes. -func (cmd *PageItemCommand) writeBytes(w io.Writer, b []byte, format string) error { - switch format { - case "ascii-encoded": - _, err := fmt.Fprintf(w, "%q", b) - if err != nil { - return err - } - _, err = fmt.Fprintf(w, "\n") - return err - case "hex": - _, err := fmt.Fprintf(w, "%x", b) - if err != nil { - return err - } - _, err = fmt.Fprintf(w, "\n") - return err - case "bytes": - _, err := w.Write(b) - return err - default: - return fmt.Errorf("writeBytes: unsupported format: %s", format) - } -} - -// PrintLeafItemKey writes the bytes of a leaf element's key. -func (cmd *PageItemCommand) PrintLeafItemKey(w io.Writer, pageBytes []byte, index uint16, format string) error { - e, err := cmd.leafPageElement(pageBytes, index) - if err != nil { - return err - } - return cmd.writeBytes(w, e.key(), format) -} - -// PrintLeafItemKey writes the bytes of a leaf element's value. -func (cmd *PageItemCommand) PrintLeafItemValue(w io.Writer, pageBytes []byte, index uint16, format string) error { - e, err := cmd.leafPageElement(pageBytes, index) - if err != nil { - return err - } - return cmd.writeBytes(w, e.value(), format) -} - -// Usage returns the help message. -func (cmd *PageItemCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt page-item [options] PATH pageid itemid - -Additional options include: - - --key-only - Print only the key - --value-only - Print only the value - --format - Output format. One of: ascii-encoded|hex|bytes (default=ascii-encoded) - -page-item prints a page item key and value. -`, "\n") -} - -// PageCommand represents the "page" command execution. -type PageCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// newPageCommand returns a PageCommand. -func newPageCommand(m *Main) *PageCommand { - return &PageCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *PageCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path and page id. - path := fs.Arg(0) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Read page ids. - pageIDs, err := atois(fs.Args()[1:]) - if err != nil { - return err - } else if len(pageIDs) == 0 { - return ErrPageIDRequired - } - - // Open database file handler. - f, err := os.Open(path) - if err != nil { - return err - } - defer func() { _ = f.Close() }() - - // Print each page listed. - for i, pageID := range pageIDs { - // Print a separator. - if i > 0 { - fmt.Fprintln(cmd.Stdout, "===============================================") - } - - // Retrieve page info and page size. - p, buf, err := ReadPage(path, pageID) - if err != nil { - return err - } - - // Print basic page info. - fmt.Fprintf(cmd.Stdout, "Page ID: %d\n", p.id) - fmt.Fprintf(cmd.Stdout, "Page Type: %s\n", p.Type()) - fmt.Fprintf(cmd.Stdout, "Total Size: %d bytes\n", len(buf)) - - // Print type-specific data. - switch p.Type() { - case "meta": - err = cmd.PrintMeta(cmd.Stdout, buf) - case "leaf": - err = cmd.PrintLeaf(cmd.Stdout, buf) - case "branch": - err = cmd.PrintBranch(cmd.Stdout, buf) - case "freelist": - err = cmd.PrintFreelist(cmd.Stdout, buf) - } - if err != nil { - return err - } - } - - return nil -} - -// PrintMeta prints the data from the meta page. -func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error { - m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) - fmt.Fprintf(w, "Version: %d\n", m.version) - fmt.Fprintf(w, "Page Size: %d bytes\n", m.pageSize) - fmt.Fprintf(w, "Flags: %08x\n", m.flags) - fmt.Fprintf(w, "Root: \n", m.root.root) - fmt.Fprintf(w, "Freelist: \n", m.freelist) - fmt.Fprintf(w, "HWM: \n", m.pgid) - fmt.Fprintf(w, "Txn ID: %d\n", m.txid) - fmt.Fprintf(w, "Checksum: %016x\n", m.checksum) - fmt.Fprintf(w, "\n") - return nil -} - -// PrintLeaf prints the data for a leaf page. -func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error { - p := (*page)(unsafe.Pointer(&buf[0])) - - // Print number of items. - fmt.Fprintf(w, "Item Count: %d\n", p.count) - fmt.Fprintf(w, "\n") - - // Print each key/value. - for i := uint16(0); i < p.count; i++ { - e := p.leafPageElement(i) - - // Format key as string. - var k string - if isPrintable(string(e.key())) { - k = fmt.Sprintf("%q", string(e.key())) - } else { - k = fmt.Sprintf("%x", string(e.key())) - } - - // Format value as string. - var v string - if (e.flags & uint32(bucketLeafFlag)) != 0 { - b := (*bucket)(unsafe.Pointer(&e.value()[0])) - v = fmt.Sprintf("", b.root, b.sequence) - } else if isPrintable(string(e.value())) { - v = fmt.Sprintf("%q", string(e.value())) - } else { - v = fmt.Sprintf("%x", string(e.value())) - } - - fmt.Fprintf(w, "%s: %s\n", k, v) - } - fmt.Fprintf(w, "\n") - return nil -} - -// PrintBranch prints the data for a leaf page. -func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error { - p := (*page)(unsafe.Pointer(&buf[0])) - - // Print number of items. - fmt.Fprintf(w, "Item Count: %d\n", p.count) - fmt.Fprintf(w, "\n") - - // Print each key/value. - for i := uint16(0); i < p.count; i++ { - e := p.branchPageElement(i) - - // Format key as string. - var k string - if isPrintable(string(e.key())) { - k = fmt.Sprintf("%q", string(e.key())) - } else { - k = fmt.Sprintf("%x", string(e.key())) - } - - fmt.Fprintf(w, "%s: \n", k, e.pgid) - } - fmt.Fprintf(w, "\n") - return nil -} - -// PrintFreelist prints the data for a freelist page. -func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error { - p := (*page)(unsafe.Pointer(&buf[0])) - - // Check for overflow and, if present, adjust starting index and actual element count. - idx, count := 0, int(p.count) - if p.count == 0xFFFF { - idx = 1 - count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0]) - } - - // Print number of items. - fmt.Fprintf(w, "Item Count: %d\n", count) - fmt.Fprintf(w, "Overflow: %d\n", p.overflow) - - fmt.Fprintf(w, "\n") - - // Print each page in the freelist. - ids := (*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)) - for i := int(idx); i < count; i++ { - fmt.Fprintf(w, "%d\n", ids[i]) - } - fmt.Fprintf(w, "\n") - return nil -} - -// PrintPage prints a given page as hexadecimal. -func (cmd *PageCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error { - const bytesPerLineN = 16 - - // Read page into buffer. - buf := make([]byte, pageSize) - addr := pageID * pageSize - if n, err := r.ReadAt(buf, int64(addr)); err != nil { - return err - } else if n != pageSize { - return io.ErrUnexpectedEOF - } - - // Write out to writer in 16-byte lines. - var prev []byte - var skipped bool - for offset := 0; offset < pageSize; offset += bytesPerLineN { - // Retrieve current 16-byte line. - line := buf[offset : offset+bytesPerLineN] - isLastLine := (offset == (pageSize - bytesPerLineN)) - - // If it's the same as the previous line then print a skip. - if bytes.Equal(line, prev) && !isLastLine { - if !skipped { - fmt.Fprintf(w, "%07x *\n", addr+offset) - skipped = true - } - } else { - // Print line as hexadecimal in 2-byte groups. - fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset, - line[0:2], line[2:4], line[4:6], line[6:8], - line[8:10], line[10:12], line[12:14], line[14:16], - ) - - skipped = false - } - - // Save the previous line. - prev = line - } - fmt.Fprint(w, "\n") - - return nil -} - -// Usage returns the help message. -func (cmd *PageCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt page PATH pageid [pageid...] - -Page prints one or more pages in human readable format. -`, "\n") -} - -// PagesCommand represents the "pages" command execution. -type PagesCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewPagesCommand returns a PagesCommand. -func newPagesCommand(m *Main) *PagesCommand { - return &PagesCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *PagesCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path. - path := fs.Arg(0) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Open database. - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return err - } - defer func() { _ = db.Close() }() - - // Write header. - fmt.Fprintln(cmd.Stdout, "ID TYPE ITEMS OVRFLW") - fmt.Fprintln(cmd.Stdout, "======== ========== ====== ======") - - return db.Update(func(tx *bolt.Tx) error { - var id int - for { - p, err := tx.Page(id) - if err != nil { - return &PageError{ID: id, Err: err} - } else if p == nil { - break - } - - // Only display count and overflow if this is a non-free page. - var count, overflow string - if p.Type != "free" { - count = strconv.Itoa(p.Count) - if p.OverflowCount > 0 { - overflow = strconv.Itoa(p.OverflowCount) - } - } - - // Print table row. - fmt.Fprintf(cmd.Stdout, "%-8d %-10s %-6s %-6s\n", p.ID, p.Type, count, overflow) - - // Move to the next non-overflow page. - id += 1 - if p.Type != "free" { - id += p.OverflowCount - } - } - return nil - }) -} - -// Usage returns the help message. -func (cmd *PagesCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt pages PATH - -Pages prints a table of pages with their type (meta, leaf, branch, freelist). -Leaf and branch pages will show a key count in the "items" column while the -freelist will show the number of free pages in the "items" column. - -The "overflow" column shows the number of blocks that the page spills over -into. Normally there is no overflow but large keys and values can cause -a single page to take up multiple blocks. -`, "\n") -} - -// StatsCommand represents the "stats" command execution. -type StatsCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewStatsCommand returns a StatsCommand. -func newStatsCommand(m *Main) *StatsCommand { - return &StatsCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *StatsCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path. - path, prefix := fs.Arg(0), fs.Arg(1) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Open database. - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return err - } - defer db.Close() - - return db.View(func(tx *bolt.Tx) error { - var s bolt.BucketStats - var count int - if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error { - if bytes.HasPrefix(name, []byte(prefix)) { - s.Add(b.Stats()) - count += 1 - } - return nil - }); err != nil { - return err - } - - fmt.Fprintf(cmd.Stdout, "Aggregate statistics for %d buckets\n\n", count) - - fmt.Fprintln(cmd.Stdout, "Page count statistics") - fmt.Fprintf(cmd.Stdout, "\tNumber of logical branch pages: %d\n", s.BranchPageN) - fmt.Fprintf(cmd.Stdout, "\tNumber of physical branch overflow pages: %d\n", s.BranchOverflowN) - fmt.Fprintf(cmd.Stdout, "\tNumber of logical leaf pages: %d\n", s.LeafPageN) - fmt.Fprintf(cmd.Stdout, "\tNumber of physical leaf overflow pages: %d\n", s.LeafOverflowN) - - fmt.Fprintln(cmd.Stdout, "Tree statistics") - fmt.Fprintf(cmd.Stdout, "\tNumber of keys/value pairs: %d\n", s.KeyN) - fmt.Fprintf(cmd.Stdout, "\tNumber of levels in B+tree: %d\n", s.Depth) - - fmt.Fprintln(cmd.Stdout, "Page size utilization") - fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical branch pages: %d\n", s.BranchAlloc) - var percentage int - if s.BranchAlloc != 0 { - percentage = int(float32(s.BranchInuse) * 100.0 / float32(s.BranchAlloc)) - } - fmt.Fprintf(cmd.Stdout, "\tBytes actually used for branch data: %d (%d%%)\n", s.BranchInuse, percentage) - fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical leaf pages: %d\n", s.LeafAlloc) - percentage = 0 - if s.LeafAlloc != 0 { - percentage = int(float32(s.LeafInuse) * 100.0 / float32(s.LeafAlloc)) - } - fmt.Fprintf(cmd.Stdout, "\tBytes actually used for leaf data: %d (%d%%)\n", s.LeafInuse, percentage) - - fmt.Fprintln(cmd.Stdout, "Bucket statistics") - fmt.Fprintf(cmd.Stdout, "\tTotal number of buckets: %d\n", s.BucketN) - percentage = 0 - if s.BucketN != 0 { - percentage = int(float32(s.InlineBucketN) * 100.0 / float32(s.BucketN)) - } - fmt.Fprintf(cmd.Stdout, "\tTotal number on inlined buckets: %d (%d%%)\n", s.InlineBucketN, percentage) - percentage = 0 - if s.LeafInuse != 0 { - percentage = int(float32(s.InlineBucketInuse) * 100.0 / float32(s.LeafInuse)) - } - fmt.Fprintf(cmd.Stdout, "\tBytes used for inlined buckets: %d (%d%%)\n", s.InlineBucketInuse, percentage) - - return nil - }) -} - -// Usage returns the help message. -func (cmd *StatsCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt stats PATH - -Stats performs an extensive search of the database to track every page -reference. It starts at the current meta page and recursively iterates -through every accessible bucket. - -The following errors can be reported: - - already freed - The page is referenced more than once in the freelist. - - unreachable unfreed - The page is not referenced by a bucket or in the freelist. - - reachable freed - The page is referenced by a bucket but is also in the freelist. - - out of bounds - A page is referenced that is above the high water mark. - - multiple references - A page is referenced by more than one other page. - - invalid type - The page type is not "meta", "leaf", "branch", or "freelist". - -No errors should occur in your database. However, if for some reason you -experience corruption, please submit a ticket to the Bolt project page: - - https://github.com/boltdb/bolt/issues -`, "\n") -} - -// BucketsCommand represents the "buckets" command execution. -type BucketsCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewBucketsCommand returns a BucketsCommand. -func newBucketsCommand(m *Main) *BucketsCommand { - return &BucketsCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *BucketsCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path. - path := fs.Arg(0) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } - - // Open database. - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return err - } - defer db.Close() - - // Print buckets. - return db.View(func(tx *bolt.Tx) error { - return tx.ForEach(func(name []byte, _ *bolt.Bucket) error { - fmt.Fprintln(cmd.Stdout, string(name)) - return nil - }) - }) -} - -// Usage returns the help message. -func (cmd *BucketsCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt buckets PATH - -Print a list of buckets. -`, "\n") -} - -// KeysCommand represents the "keys" command execution. -type KeysCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewKeysCommand returns a KeysCommand. -func newKeysCommand(m *Main) *KeysCommand { - return &KeysCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *KeysCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path and bucket. - path, bucket := fs.Arg(0), fs.Arg(1) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } else if bucket == "" { - return ErrBucketRequired - } - - // Open database. - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return err - } - defer db.Close() - - // Print keys. - return db.View(func(tx *bolt.Tx) error { - // Find bucket. - b := tx.Bucket([]byte(bucket)) - if b == nil { - return ErrBucketNotFound - } - - // Iterate over each key. - return b.ForEach(func(key, _ []byte) error { - fmt.Fprintln(cmd.Stdout, string(key)) - return nil - }) - }) -} - -// Usage returns the help message. -func (cmd *KeysCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt keys PATH BUCKET - -Print a list of keys in the given bucket. -`, "\n") -} - -// GetCommand represents the "get" command execution. -type GetCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewGetCommand returns a GetCommand. -func newGetCommand(m *Main) *GetCommand { - return &GetCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *GetCommand) Run(args ...string) error { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - help := fs.Bool("h", false, "") - if err := fs.Parse(args); err != nil { - return err - } else if *help { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } - - // Require database path, bucket and key. - path, bucket, key := fs.Arg(0), fs.Arg(1), fs.Arg(2) - if path == "" { - return ErrPathRequired - } else if _, err := os.Stat(path); os.IsNotExist(err) { - return ErrFileNotFound - } else if bucket == "" { - return ErrBucketRequired - } else if key == "" { - return ErrKeyRequired - } - - // Open database. - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return err - } - defer db.Close() - - // Print value. - return db.View(func(tx *bolt.Tx) error { - // Find bucket. - b := tx.Bucket([]byte(bucket)) - if b == nil { - return ErrBucketNotFound - } - - // Find value for given key. - val := b.Get([]byte(key)) - if val == nil { - return ErrKeyNotFound - } - - fmt.Fprintln(cmd.Stdout, string(val)) - return nil - }) -} - -// Usage returns the help message. -func (cmd *GetCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt get PATH BUCKET KEY - -Print the value of the given key in the given bucket. -`, "\n") -} - -var benchBucketName = []byte("bench") - -// BenchCommand represents the "bench" command execution. -type BenchCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewBenchCommand returns a BenchCommand using the -func newBenchCommand(m *Main) *BenchCommand { - return &BenchCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the "bench" command. -func (cmd *BenchCommand) Run(args ...string) error { - // Parse CLI arguments. - options, err := cmd.ParseFlags(args) - if err != nil { - return err - } - - // Remove path if "-work" is not set. Otherwise keep path. - if options.Work { - fmt.Fprintf(cmd.Stdout, "work: %s\n", options.Path) - } else { - defer os.Remove(options.Path) - } - - // Create database. - db, err := bolt.Open(options.Path, 0666, nil) - if err != nil { - return err - } - db.NoSync = options.NoSync - defer db.Close() - - // Write to the database. - var results BenchResults - if err := cmd.runWrites(db, options, &results); err != nil { - return fmt.Errorf("write: %v", err) - } - - // Read from the database. - if err := cmd.runReads(db, options, &results); err != nil { - return fmt.Errorf("bench: read: %s", err) - } - - // Print results. - fmt.Fprintf(os.Stderr, "# Write\t%v\t(%v/op)\t(%v op/sec)\n", results.WriteDuration, results.WriteOpDuration(), results.WriteOpsPerSecond()) - fmt.Fprintf(os.Stderr, "# Read\t%v\t(%v/op)\t(%v op/sec)\n", results.ReadDuration, results.ReadOpDuration(), results.ReadOpsPerSecond()) - fmt.Fprintln(os.Stderr, "") - return nil -} - -// ParseFlags parses the command line flags. -func (cmd *BenchCommand) ParseFlags(args []string) (*BenchOptions, error) { - var options BenchOptions - - // Parse flagset. - fs := flag.NewFlagSet("", flag.ContinueOnError) - fs.StringVar(&options.ProfileMode, "profile-mode", "rw", "") - fs.StringVar(&options.WriteMode, "write-mode", "seq", "") - fs.StringVar(&options.ReadMode, "read-mode", "seq", "") - fs.IntVar(&options.Iterations, "count", 1000, "") - fs.IntVar(&options.BatchSize, "batch-size", 0, "") - fs.IntVar(&options.KeySize, "key-size", 8, "") - fs.IntVar(&options.ValueSize, "value-size", 32, "") - fs.StringVar(&options.CPUProfile, "cpuprofile", "", "") - fs.StringVar(&options.MemProfile, "memprofile", "", "") - fs.StringVar(&options.BlockProfile, "blockprofile", "", "") - fs.Float64Var(&options.FillPercent, "fill-percent", bolt.DefaultFillPercent, "") - fs.BoolVar(&options.NoSync, "no-sync", false, "") - fs.BoolVar(&options.Work, "work", false, "") - fs.StringVar(&options.Path, "path", "", "") - fs.SetOutput(cmd.Stderr) - if err := fs.Parse(args); err != nil { - return nil, err - } - - // Set batch size to iteration size if not set. - // Require that batch size can be evenly divided by the iteration count. - if options.BatchSize == 0 { - options.BatchSize = options.Iterations - } else if options.Iterations%options.BatchSize != 0 { - return nil, ErrNonDivisibleBatchSize - } - - // Generate temp path if one is not passed in. - if options.Path == "" { - f, err := ioutil.TempFile("", "bolt-bench-") - if err != nil { - return nil, fmt.Errorf("temp file: %s", err) - } - f.Close() - os.Remove(f.Name()) - options.Path = f.Name() - } - - return &options, nil -} - -// Writes to the database. -func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - // Start profiling for writes. - if options.ProfileMode == "rw" || options.ProfileMode == "w" { - cmd.startProfiling(options) - } - - t := time.Now() - - var err error - switch options.WriteMode { - case "seq": - err = cmd.runWritesSequential(db, options, results) - case "rnd": - err = cmd.runWritesRandom(db, options, results) - case "seq-nest": - err = cmd.runWritesSequentialNested(db, options, results) - case "rnd-nest": - err = cmd.runWritesRandomNested(db, options, results) - default: - return fmt.Errorf("invalid write mode: %s", options.WriteMode) - } - - // Save time to write. - results.WriteDuration = time.Since(t) - - // Stop profiling for writes only. - if options.ProfileMode == "w" { - cmd.stopProfiling() - } - - return err -} - -func (cmd *BenchCommand) runWritesSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - var i = uint32(0) - return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i }) -} - -func (cmd *BenchCommand) runWritesRandom(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() }) -} - -func (cmd *BenchCommand) runWritesSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - var i = uint32(0) - return cmd.runWritesNestedWithSource(db, options, results, func() uint32 { i++; return i }) -} - -func (cmd *BenchCommand) runWritesRandomNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - return cmd.runWritesNestedWithSource(db, options, results, func() uint32 { return r.Uint32() }) -} - -func (cmd *BenchCommand) runWritesWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error { - results.WriteOps = options.Iterations - - for i := 0; i < options.Iterations; i += options.BatchSize { - if err := db.Update(func(tx *bolt.Tx) error { - b, _ := tx.CreateBucketIfNotExists(benchBucketName) - b.FillPercent = options.FillPercent - - for j := 0; j < options.BatchSize; j++ { - key := make([]byte, options.KeySize) - value := make([]byte, options.ValueSize) - - // Write key as uint32. - binary.BigEndian.PutUint32(key, keySource()) - - // Insert key/value. - if err := b.Put(key, value); err != nil { - return err - } - } - - return nil - }); err != nil { - return err - } - } - return nil -} - -func (cmd *BenchCommand) runWritesNestedWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error { - results.WriteOps = options.Iterations - - for i := 0; i < options.Iterations; i += options.BatchSize { - if err := db.Update(func(tx *bolt.Tx) error { - top, err := tx.CreateBucketIfNotExists(benchBucketName) - if err != nil { - return err - } - top.FillPercent = options.FillPercent - - // Create bucket key. - name := make([]byte, options.KeySize) - binary.BigEndian.PutUint32(name, keySource()) - - // Create bucket. - b, err := top.CreateBucketIfNotExists(name) - if err != nil { - return err - } - b.FillPercent = options.FillPercent - - for j := 0; j < options.BatchSize; j++ { - var key = make([]byte, options.KeySize) - var value = make([]byte, options.ValueSize) - - // Generate key as uint32. - binary.BigEndian.PutUint32(key, keySource()) - - // Insert value into subbucket. - if err := b.Put(key, value); err != nil { - return err - } - } - - return nil - }); err != nil { - return err - } - } - return nil -} - -// Reads from the database. -func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - // Start profiling for reads. - if options.ProfileMode == "r" { - cmd.startProfiling(options) - } - - t := time.Now() - - var err error - switch options.ReadMode { - case "seq": - switch options.WriteMode { - case "seq-nest", "rnd-nest": - err = cmd.runReadsSequentialNested(db, options, results) - default: - err = cmd.runReadsSequential(db, options, results) - } - default: - return fmt.Errorf("invalid read mode: %s", options.ReadMode) - } - - // Save read time. - results.ReadDuration = time.Since(t) - - // Stop profiling for reads. - if options.ProfileMode == "rw" || options.ProfileMode == "r" { - cmd.stopProfiling() - } - - return err -} - -func (cmd *BenchCommand) runReadsSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - return db.View(func(tx *bolt.Tx) error { - t := time.Now() - - for { - var count int - - c := tx.Bucket(benchBucketName).Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - if v == nil { - return errors.New("invalid value") - } - count++ - } - - if options.WriteMode == "seq" && count != options.Iterations { - return fmt.Errorf("read seq: iter mismatch: expected %d, got %d", options.Iterations, count) - } - - results.ReadOps += count - - // Make sure we do this for at least a second. - if time.Since(t) >= time.Second { - break - } - } - - return nil - }) -} - -func (cmd *BenchCommand) runReadsSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error { - return db.View(func(tx *bolt.Tx) error { - t := time.Now() - - for { - var count int - var top = tx.Bucket(benchBucketName) - if err := top.ForEach(func(name, _ []byte) error { - if b := top.Bucket(name); b != nil { - c := b.Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - if v == nil { - return ErrInvalidValue - } - count++ - } - } - return nil - }); err != nil { - return err - } - - if options.WriteMode == "seq-nest" && count != options.Iterations { - return fmt.Errorf("read seq-nest: iter mismatch: expected %d, got %d", options.Iterations, count) - } - - results.ReadOps += count - - // Make sure we do this for at least a second. - if time.Since(t) >= time.Second { - break - } - } - - return nil - }) -} - -// File handlers for the various profiles. -var cpuprofile, memprofile, blockprofile *os.File - -// Starts all profiles set on the options. -func (cmd *BenchCommand) startProfiling(options *BenchOptions) { - var err error - - // Start CPU profiling. - if options.CPUProfile != "" { - cpuprofile, err = os.Create(options.CPUProfile) - if err != nil { - fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err) - os.Exit(1) - } - pprof.StartCPUProfile(cpuprofile) - } - - // Start memory profiling. - if options.MemProfile != "" { - memprofile, err = os.Create(options.MemProfile) - if err != nil { - fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err) - os.Exit(1) - } - runtime.MemProfileRate = 4096 - } - - // Start fatal profiling. - if options.BlockProfile != "" { - blockprofile, err = os.Create(options.BlockProfile) - if err != nil { - fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err) - os.Exit(1) - } - runtime.SetBlockProfileRate(1) - } -} - -// Stops all profiles. -func (cmd *BenchCommand) stopProfiling() { - if cpuprofile != nil { - pprof.StopCPUProfile() - cpuprofile.Close() - cpuprofile = nil - } - - if memprofile != nil { - pprof.Lookup("heap").WriteTo(memprofile, 0) - memprofile.Close() - memprofile = nil - } - - if blockprofile != nil { - pprof.Lookup("block").WriteTo(blockprofile, 0) - blockprofile.Close() - blockprofile = nil - runtime.SetBlockProfileRate(0) - } -} - -// BenchOptions represents the set of options that can be passed to "bolt bench". -type BenchOptions struct { - ProfileMode string - WriteMode string - ReadMode string - Iterations int - BatchSize int - KeySize int - ValueSize int - CPUProfile string - MemProfile string - BlockProfile string - StatsInterval time.Duration - FillPercent float64 - NoSync bool - Work bool - Path string -} - -// BenchResults represents the performance results of the benchmark. -type BenchResults struct { - WriteOps int - WriteDuration time.Duration - ReadOps int - ReadDuration time.Duration -} - -// Returns the duration for a single write operation. -func (r *BenchResults) WriteOpDuration() time.Duration { - if r.WriteOps == 0 { - return 0 - } - return r.WriteDuration / time.Duration(r.WriteOps) -} - -// Returns average number of write operations that can be performed per second. -func (r *BenchResults) WriteOpsPerSecond() int { - var op = r.WriteOpDuration() - if op == 0 { - return 0 - } - return int(time.Second) / int(op) -} - -// Returns the duration for a single read operation. -func (r *BenchResults) ReadOpDuration() time.Duration { - if r.ReadOps == 0 { - return 0 - } - return r.ReadDuration / time.Duration(r.ReadOps) -} - -// Returns average number of read operations that can be performed per second. -func (r *BenchResults) ReadOpsPerSecond() int { - var op = r.ReadOpDuration() - if op == 0 { - return 0 - } - return int(time.Second) / int(op) -} - -type PageError struct { - ID int - Err error -} - -func (e *PageError) Error() string { - return fmt.Sprintf("page error: id=%d, err=%s", e.ID, e.Err) -} - -// isPrintable returns true if the string is valid unicode and contains only printable runes. -func isPrintable(s string) bool { - if !utf8.ValidString(s) { - return false - } - for _, ch := range s { - if !unicode.IsPrint(ch) { - return false - } - } - return true -} - -// ReadPage reads page info & full page data from a path. -// This is not transactionally safe. -func ReadPage(path string, pageID int) (*page, []byte, error) { - // Find page size. - pageSize, err := ReadPageSize(path) - if err != nil { - return nil, nil, fmt.Errorf("read page size: %s", err) - } - - // Open database file. - f, err := os.Open(path) - if err != nil { - return nil, nil, err - } - defer f.Close() - - // Read one block into buffer. - buf := make([]byte, pageSize) - if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { - return nil, nil, err - } else if n != len(buf) { - return nil, nil, io.ErrUnexpectedEOF - } - - // Determine total number of blocks. - p := (*page)(unsafe.Pointer(&buf[0])) - overflowN := p.overflow - - // Re-read entire page (with overflow) into buffer. - buf = make([]byte, (int(overflowN)+1)*pageSize) - if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil { - return nil, nil, err - } else if n != len(buf) { - return nil, nil, io.ErrUnexpectedEOF - } - p = (*page)(unsafe.Pointer(&buf[0])) - - return p, buf, nil -} - -// ReadPageSize reads page size a path. -// This is not transactionally safe. -func ReadPageSize(path string) (int, error) { - // Open database file. - f, err := os.Open(path) - if err != nil { - return 0, err - } - defer f.Close() - - // Read 4KB chunk. - buf := make([]byte, 4096) - if _, err := io.ReadFull(f, buf); err != nil { - return 0, err - } - - // Read page size from metadata. - m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize])) - return int(m.pageSize), nil -} - -// atois parses a slice of strings into integers. -func atois(strs []string) ([]int, error) { - var a []int - for _, str := range strs { - i, err := strconv.Atoi(str) - if err != nil { - return nil, err - } - a = append(a, i) - } - return a, nil -} - -// DO NOT EDIT. Copied from the "bolt" package. -const maxAllocSize = 0xFFFFFFF - -// DO NOT EDIT. Copied from the "bolt" package. -const ( - branchPageFlag = 0x01 - leafPageFlag = 0x02 - metaPageFlag = 0x04 - freelistPageFlag = 0x10 -) - -// DO NOT EDIT. Copied from the "bolt" package. -const bucketLeafFlag = 0x01 - -// DO NOT EDIT. Copied from the "bolt" package. -type pgid uint64 - -// DO NOT EDIT. Copied from the "bolt" package. -type txid uint64 - -// DO NOT EDIT. Copied from the "bolt" package. -type meta struct { - magic uint32 - version uint32 - pageSize uint32 - flags uint32 - root bucket - freelist pgid - pgid pgid - txid txid - checksum uint64 -} - -// DO NOT EDIT. Copied from the "bolt" package. -type bucket struct { - root pgid - sequence uint64 -} - -// DO NOT EDIT. Copied from the "bolt" package. -type page struct { - id pgid - flags uint16 - count uint16 - overflow uint32 - ptr uintptr -} - -// DO NOT EDIT. Copied from the "bolt" package. -func (p *page) Type() string { - if (p.flags & branchPageFlag) != 0 { - return "branch" - } else if (p.flags & leafPageFlag) != 0 { - return "leaf" - } else if (p.flags & metaPageFlag) != 0 { - return "meta" - } else if (p.flags & freelistPageFlag) != 0 { - return "freelist" - } - return fmt.Sprintf("unknown<%02x>", p.flags) -} - -// DO NOT EDIT. Copied from the "bolt" package. -func (p *page) leafPageElement(index uint16) *leafPageElement { - n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index] - return n -} - -// DO NOT EDIT. Copied from the "bolt" package. -func (p *page) branchPageElement(index uint16) *branchPageElement { - return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index] -} - -// DO NOT EDIT. Copied from the "bolt" package. -type branchPageElement struct { - pos uint32 - ksize uint32 - pgid pgid -} - -// DO NOT EDIT. Copied from the "bolt" package. -func (n *branchPageElement) key() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return buf[n.pos : n.pos+n.ksize] -} - -// DO NOT EDIT. Copied from the "bolt" package. -type leafPageElement struct { - flags uint32 - pos uint32 - ksize uint32 - vsize uint32 -} - -// DO NOT EDIT. Copied from the "bolt" package. -func (n *leafPageElement) key() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return buf[n.pos : n.pos+n.ksize] -} - -// DO NOT EDIT. Copied from the "bolt" package. -func (n *leafPageElement) value() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return buf[n.pos+n.ksize : n.pos+n.ksize+n.vsize] -} - -// CompactCommand represents the "compact" command execution. -type CompactCommand struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer - - SrcPath string - DstPath string - TxMaxSize int64 -} - -// newCompactCommand returns a CompactCommand. -func newCompactCommand(m *Main) *CompactCommand { - return &CompactCommand{ - Stdin: m.Stdin, - Stdout: m.Stdout, - Stderr: m.Stderr, - } -} - -// Run executes the command. -func (cmd *CompactCommand) Run(args ...string) (err error) { - // Parse flags. - fs := flag.NewFlagSet("", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - fs.StringVar(&cmd.DstPath, "o", "", "") - fs.Int64Var(&cmd.TxMaxSize, "tx-max-size", 65536, "") - if err := fs.Parse(args); err == flag.ErrHelp { - fmt.Fprintln(cmd.Stderr, cmd.Usage()) - return ErrUsage - } else if err != nil { - return err - } else if cmd.DstPath == "" { - return fmt.Errorf("output file required") - } - - // Require database paths. - cmd.SrcPath = fs.Arg(0) - if cmd.SrcPath == "" { - return ErrPathRequired - } - - // Ensure source file exists. - fi, err := os.Stat(cmd.SrcPath) - if os.IsNotExist(err) { - return ErrFileNotFound - } else if err != nil { - return err - } - initialSize := fi.Size() - - // Open source database. - src, err := bolt.Open(cmd.SrcPath, 0444, nil) - if err != nil { - return err - } - defer src.Close() - - // Open destination database. - dst, err := bolt.Open(cmd.DstPath, fi.Mode(), nil) - if err != nil { - return err - } - defer dst.Close() - - // Run compaction. - if err := cmd.compact(dst, src); err != nil { - return err - } - - // Report stats on new size. - fi, err = os.Stat(cmd.DstPath) - if err != nil { - return err - } else if fi.Size() == 0 { - return fmt.Errorf("zero db size") - } - fmt.Fprintf(cmd.Stdout, "%d -> %d bytes (gain=%.2fx)\n", initialSize, fi.Size(), float64(initialSize)/float64(fi.Size())) - - return nil -} - -func (cmd *CompactCommand) compact(dst, src *bolt.DB) error { - // commit regularly, or we'll run out of memory for large datasets if using one transaction. - var size int64 - tx, err := dst.Begin(true) - if err != nil { - return err - } - defer tx.Rollback() - - if err := cmd.walk(src, func(keys [][]byte, k, v []byte, seq uint64) error { - // On each key/value, check if we have exceeded tx size. - sz := int64(len(k) + len(v)) - if size+sz > cmd.TxMaxSize && cmd.TxMaxSize != 0 { - // Commit previous transaction. - if err := tx.Commit(); err != nil { - return err - } - - // Start new transaction. - tx, err = dst.Begin(true) - if err != nil { - return err - } - size = 0 - } - size += sz - - // Create bucket on the root transaction if this is the first level. - nk := len(keys) - if nk == 0 { - bkt, err := tx.CreateBucket(k) - if err != nil { - return err - } - if err := bkt.SetSequence(seq); err != nil { - return err - } - return nil - } - - // Create buckets on subsequent levels, if necessary. - b := tx.Bucket(keys[0]) - if nk > 1 { - for _, k := range keys[1:] { - b = b.Bucket(k) - } - } - - // Fill the entire page for best compaction. - b.FillPercent = 1.0 - - // If there is no value then this is a bucket call. - if v == nil { - bkt, err := b.CreateBucket(k) - if err != nil { - return err - } - if err := bkt.SetSequence(seq); err != nil { - return err - } - return nil - } - - // Otherwise treat it as a key/value pair. - return b.Put(k, v) - }); err != nil { - return err - } - - return tx.Commit() -} - -// walkFunc is the type of the function called for keys (buckets and "normal" -// values) discovered by Walk. keys is the list of keys to descend to the bucket -// owning the discovered key/value pair k/v. -type walkFunc func(keys [][]byte, k, v []byte, seq uint64) error - -// walk walks recursively the bolt database db, calling walkFn for each key it finds. -func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error { - return db.View(func(tx *bolt.Tx) error { - return tx.ForEach(func(name []byte, b *bolt.Bucket) error { - return cmd.walkBucket(b, nil, name, nil, b.Sequence(), walkFn) - }) - }) -} - -func (cmd *CompactCommand) walkBucket(b *bolt.Bucket, keypath [][]byte, k, v []byte, seq uint64, fn walkFunc) error { - // Execute callback. - if err := fn(keypath, k, v, seq); err != nil { - return err - } - - // If this is not a bucket then stop. - if v != nil { - return nil - } - - // Iterate over each child key/value. - keypath = append(keypath, k) - return b.ForEach(func(k, v []byte) error { - if v == nil { - bkt := b.Bucket(k) - return cmd.walkBucket(bkt, keypath, k, nil, bkt.Sequence(), fn) - } - return cmd.walkBucket(b, keypath, k, v, b.Sequence(), fn) - }) -} - -// Usage returns the help message. -func (cmd *CompactCommand) Usage() string { - return strings.TrimLeft(` -usage: bolt compact [options] -o DST SRC - -Compact opens a database at SRC path and walks it recursively, copying keys -as they are found from all buckets, to a newly created database at DST path. - -The original database is left untouched. - -Additional options include: - - -tx-max-size NUM - Specifies the maximum size of individual transactions. - Defaults to 64KB. -`, "\n") -} diff --git a/vendor/github.com/coreos/bbolt/cmd/bolt/main_test.go b/vendor/github.com/coreos/bbolt/cmd/bolt/main_test.go deleted file mode 100644 index 16bf804..0000000 --- a/vendor/github.com/coreos/bbolt/cmd/bolt/main_test.go +++ /dev/null @@ -1,456 +0,0 @@ -package main_test - -import ( - "bytes" - crypto "crypto/rand" - "encoding/binary" - "fmt" - "io" - "io/ioutil" - "math/rand" - "os" - "strconv" - "testing" - - "github.com/coreos/bbolt" - "github.com/coreos/bbolt/cmd/bolt" -) - -// Ensure the "info" command can print information about a database. -func TestInfoCommand_Run(t *testing.T) { - db := MustOpen(0666, nil) - db.DB.Close() - defer db.Close() - - // Run the info command. - m := NewMain() - if err := m.Run("info", db.Path); err != nil { - t.Fatal(err) - } -} - -// Ensure the "stats" command executes correctly with an empty database. -func TestStatsCommand_Run_EmptyDatabase(t *testing.T) { - // Ignore - if os.Getpagesize() != 4096 { - t.Skip("system does not use 4KB page size") - } - - db := MustOpen(0666, nil) - defer db.Close() - db.DB.Close() - - // Generate expected result. - exp := "Aggregate statistics for 0 buckets\n\n" + - "Page count statistics\n" + - "\tNumber of logical branch pages: 0\n" + - "\tNumber of physical branch overflow pages: 0\n" + - "\tNumber of logical leaf pages: 0\n" + - "\tNumber of physical leaf overflow pages: 0\n" + - "Tree statistics\n" + - "\tNumber of keys/value pairs: 0\n" + - "\tNumber of levels in B+tree: 0\n" + - "Page size utilization\n" + - "\tBytes allocated for physical branch pages: 0\n" + - "\tBytes actually used for branch data: 0 (0%)\n" + - "\tBytes allocated for physical leaf pages: 0\n" + - "\tBytes actually used for leaf data: 0 (0%)\n" + - "Bucket statistics\n" + - "\tTotal number of buckets: 0\n" + - "\tTotal number on inlined buckets: 0 (0%)\n" + - "\tBytes used for inlined buckets: 0 (0%)\n" - - // Run the command. - m := NewMain() - if err := m.Run("stats", db.Path); err != nil { - t.Fatal(err) - } else if m.Stdout.String() != exp { - t.Fatalf("unexpected stdout:\n\n%s", m.Stdout.String()) - } -} - -// Ensure the "stats" command can execute correctly. -func TestStatsCommand_Run(t *testing.T) { - // Ignore - if os.Getpagesize() != 4096 { - t.Skip("system does not use 4KB page size") - } - - db := MustOpen(0666, nil) - defer db.Close() - - if err := db.Update(func(tx *bolt.Tx) error { - // Create "foo" bucket. - b, err := tx.CreateBucket([]byte("foo")) - if err != nil { - return err - } - for i := 0; i < 10; i++ { - if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - return err - } - } - - // Create "bar" bucket. - b, err = tx.CreateBucket([]byte("bar")) - if err != nil { - return err - } - for i := 0; i < 100; i++ { - if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - return err - } - } - - // Create "baz" bucket. - b, err = tx.CreateBucket([]byte("baz")) - if err != nil { - return err - } - if err := b.Put([]byte("key"), []byte("value")); err != nil { - return err - } - - return nil - }); err != nil { - t.Fatal(err) - } - db.DB.Close() - - // Generate expected result. - exp := "Aggregate statistics for 3 buckets\n\n" + - "Page count statistics\n" + - "\tNumber of logical branch pages: 0\n" + - "\tNumber of physical branch overflow pages: 0\n" + - "\tNumber of logical leaf pages: 1\n" + - "\tNumber of physical leaf overflow pages: 0\n" + - "Tree statistics\n" + - "\tNumber of keys/value pairs: 111\n" + - "\tNumber of levels in B+tree: 1\n" + - "Page size utilization\n" + - "\tBytes allocated for physical branch pages: 0\n" + - "\tBytes actually used for branch data: 0 (0%)\n" + - "\tBytes allocated for physical leaf pages: 4096\n" + - "\tBytes actually used for leaf data: 1996 (48%)\n" + - "Bucket statistics\n" + - "\tTotal number of buckets: 3\n" + - "\tTotal number on inlined buckets: 2 (66%)\n" + - "\tBytes used for inlined buckets: 236 (11%)\n" - - // Run the command. - m := NewMain() - if err := m.Run("stats", db.Path); err != nil { - t.Fatal(err) - } else if m.Stdout.String() != exp { - t.Fatalf("unexpected stdout:\n\n%s", m.Stdout.String()) - } -} - -// Ensure the "buckets" command can print a list of buckets. -func TestBucketsCommand_Run(t *testing.T) { - db := MustOpen(0666, nil) - defer db.Close() - - if err := db.Update(func(tx *bolt.Tx) error { - for _, name := range []string{"foo", "bar", "baz"} { - _, err := tx.CreateBucket([]byte(name)) - if err != nil { - return err - } - } - return nil - }); err != nil { - t.Fatal(err) - } - db.DB.Close() - - expected := "bar\nbaz\nfoo\n" - - // Run the command. - m := NewMain() - if err := m.Run("buckets", db.Path); err != nil { - t.Fatal(err) - } else if actual := m.Stdout.String(); actual != expected { - t.Fatalf("unexpected stdout:\n\n%s", actual) - } -} - -// Ensure the "keys" command can print a list of keys for a bucket. -func TestKeysCommand_Run(t *testing.T) { - db := MustOpen(0666, nil) - defer db.Close() - - if err := db.Update(func(tx *bolt.Tx) error { - for _, name := range []string{"foo", "bar"} { - b, err := tx.CreateBucket([]byte(name)) - if err != nil { - return err - } - for i := 0; i < 3; i++ { - key := fmt.Sprintf("%s-%d", name, i) - if err := b.Put([]byte(key), []byte{0}); err != nil { - return err - } - } - } - return nil - }); err != nil { - t.Fatal(err) - } - db.DB.Close() - - expected := "foo-0\nfoo-1\nfoo-2\n" - - // Run the command. - m := NewMain() - if err := m.Run("keys", db.Path, "foo"); err != nil { - t.Fatal(err) - } else if actual := m.Stdout.String(); actual != expected { - t.Fatalf("unexpected stdout:\n\n%s", actual) - } -} - -// Ensure the "get" command can print the value of a key in a bucket. -func TestGetCommand_Run(t *testing.T) { - db := MustOpen(0666, nil) - defer db.Close() - - if err := db.Update(func(tx *bolt.Tx) error { - for _, name := range []string{"foo", "bar"} { - b, err := tx.CreateBucket([]byte(name)) - if err != nil { - return err - } - for i := 0; i < 3; i++ { - key := fmt.Sprintf("%s-%d", name, i) - val := fmt.Sprintf("val-%s-%d", name, i) - if err := b.Put([]byte(key), []byte(val)); err != nil { - return err - } - } - } - return nil - }); err != nil { - t.Fatal(err) - } - db.DB.Close() - - expected := "val-foo-1\n" - - // Run the command. - m := NewMain() - if err := m.Run("get", db.Path, "foo", "foo-1"); err != nil { - t.Fatal(err) - } else if actual := m.Stdout.String(); actual != expected { - t.Fatalf("unexpected stdout:\n\n%s", actual) - } -} - -// Main represents a test wrapper for main.Main that records output. -type Main struct { - *main.Main - Stdin bytes.Buffer - Stdout bytes.Buffer - Stderr bytes.Buffer -} - -// NewMain returns a new instance of Main. -func NewMain() *Main { - m := &Main{Main: main.NewMain()} - m.Main.Stdin = &m.Stdin - m.Main.Stdout = &m.Stdout - m.Main.Stderr = &m.Stderr - return m -} - -// MustOpen creates a Bolt database in a temporary location. -func MustOpen(mode os.FileMode, options *bolt.Options) *DB { - // Create temporary path. - f, _ := ioutil.TempFile("", "bolt-") - f.Close() - os.Remove(f.Name()) - - db, err := bolt.Open(f.Name(), mode, options) - if err != nil { - panic(err.Error()) - } - return &DB{DB: db, Path: f.Name()} -} - -// DB is a test wrapper for bolt.DB. -type DB struct { - *bolt.DB - Path string -} - -// Close closes and removes the database. -func (db *DB) Close() error { - defer os.Remove(db.Path) - return db.DB.Close() -} - -func TestCompactCommand_Run(t *testing.T) { - var s int64 - if err := binary.Read(crypto.Reader, binary.BigEndian, &s); err != nil { - t.Fatal(err) - } - rand.Seed(s) - - dstdb := MustOpen(0666, nil) - dstdb.Close() - - // fill the db - db := MustOpen(0666, nil) - if err := db.Update(func(tx *bolt.Tx) error { - n := 2 + rand.Intn(5) - for i := 0; i < n; i++ { - k := []byte(fmt.Sprintf("b%d", i)) - b, err := tx.CreateBucketIfNotExists(k) - if err != nil { - return err - } - if err := b.SetSequence(uint64(i)); err != nil { - return err - } - if err := fillBucket(b, append(k, '.')); err != nil { - return err - } - } - return nil - }); err != nil { - db.Close() - t.Fatal(err) - } - - // make the db grow by adding large values, and delete them. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("large_vals")) - if err != nil { - return err - } - n := 5 + rand.Intn(5) - for i := 0; i < n; i++ { - v := make([]byte, 1000*1000*(1+rand.Intn(5))) - _, err := crypto.Read(v) - if err != nil { - return err - } - if err := b.Put([]byte(fmt.Sprintf("l%d", i)), v); err != nil { - return err - } - } - return nil - }); err != nil { - db.Close() - t.Fatal(err) - } - if err := db.Update(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("large_vals")).Cursor() - for k, _ := c.First(); k != nil; k, _ = c.Next() { - if err := c.Delete(); err != nil { - return err - } - } - return tx.DeleteBucket([]byte("large_vals")) - }); err != nil { - db.Close() - t.Fatal(err) - } - db.DB.Close() - defer db.Close() - defer dstdb.Close() - - dbChk, err := chkdb(db.Path) - if err != nil { - t.Fatal(err) - } - - m := NewMain() - if err := m.Run("compact", "-o", dstdb.Path, db.Path); err != nil { - t.Fatal(err) - } - - dbChkAfterCompact, err := chkdb(db.Path) - if err != nil { - t.Fatal(err) - } - - dstdbChk, err := chkdb(dstdb.Path) - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(dbChk, dbChkAfterCompact) { - t.Error("the original db has been touched") - } - if !bytes.Equal(dbChk, dstdbChk) { - t.Error("the compacted db data isn't the same than the original db") - } -} - -func fillBucket(b *bolt.Bucket, prefix []byte) error { - n := 10 + rand.Intn(50) - for i := 0; i < n; i++ { - v := make([]byte, 10*(1+rand.Intn(4))) - _, err := crypto.Read(v) - if err != nil { - return err - } - k := append(prefix, []byte(fmt.Sprintf("k%d", i))...) - if err := b.Put(k, v); err != nil { - return err - } - } - // limit depth of subbuckets - s := 2 + rand.Intn(4) - if len(prefix) > (2*s + 1) { - return nil - } - n = 1 + rand.Intn(3) - for i := 0; i < n; i++ { - k := append(prefix, []byte(fmt.Sprintf("b%d", i))...) - sb, err := b.CreateBucket(k) - if err != nil { - return err - } - if err := fillBucket(sb, append(k, '.')); err != nil { - return err - } - } - return nil -} - -func chkdb(path string) ([]byte, error) { - db, err := bolt.Open(path, 0666, nil) - if err != nil { - return nil, err - } - defer db.Close() - var buf bytes.Buffer - err = db.View(func(tx *bolt.Tx) error { - return tx.ForEach(func(name []byte, b *bolt.Bucket) error { - return walkBucket(b, name, nil, &buf) - }) - }) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -func walkBucket(parent *bolt.Bucket, k []byte, v []byte, w io.Writer) error { - if _, err := fmt.Fprintf(w, "%d:%x=%x\n", parent.Sequence(), k, v); err != nil { - return err - } - - // not a bucket, exit. - if v != nil { - return nil - } - return parent.ForEach(func(k, v []byte) error { - if v == nil { - return walkBucket(parent.Bucket(k), k, nil, w) - } - return walkBucket(parent, k, v, w) - }) -} diff --git a/vendor/github.com/coreos/bbolt/cursor.go b/vendor/github.com/coreos/bbolt/cursor.go deleted file mode 100644 index 1bdda63..0000000 --- a/vendor/github.com/coreos/bbolt/cursor.go +++ /dev/null @@ -1,396 +0,0 @@ -package bolt - -import ( - "bytes" - "fmt" - "sort" -) - -// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order. -// Cursors see nested buckets with value == nil. -// Cursors can be obtained from a transaction and are valid as long as the transaction is open. -// -// Keys and values returned from the cursor are only valid for the life of the transaction. -// -// Changing data while traversing with a cursor may cause it to be invalidated -// and return unexpected keys and/or values. You must reposition your cursor -// after mutating data. -type Cursor struct { - bucket *Bucket - stack []elemRef -} - -// Bucket returns the bucket that this cursor was created from. -func (c *Cursor) Bucket() *Bucket { - return c.bucket -} - -// First moves the cursor to the first item in the bucket and returns its key and value. -// If the bucket is empty then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) First() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - c.stack = c.stack[:0] - p, n := c.bucket.pageNode(c.bucket.root) - c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) - c.first() - - // If we land on an empty page then move to the next value. - // https://github.com/boltdb/bolt/issues/450 - if c.stack[len(c.stack)-1].count() == 0 { - c.next() - } - - k, v, flags := c.keyValue() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v - -} - -// Last moves the cursor to the last item in the bucket and returns its key and value. -// If the bucket is empty then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Last() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - c.stack = c.stack[:0] - p, n := c.bucket.pageNode(c.bucket.root) - ref := elemRef{page: p, node: n} - ref.index = ref.count() - 1 - c.stack = append(c.stack, ref) - c.last() - k, v, flags := c.keyValue() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Next moves the cursor to the next item in the bucket and returns its key and value. -// If the cursor is at the end of the bucket then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Next() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - k, v, flags := c.next() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Prev moves the cursor to the previous item in the bucket and returns its key and value. -// If the cursor is at the beginning of the bucket then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Prev() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - - // Attempt to move back one element until we're successful. - // Move up the stack as we hit the beginning of each page in our stack. - for i := len(c.stack) - 1; i >= 0; i-- { - elem := &c.stack[i] - if elem.index > 0 { - elem.index-- - break - } - c.stack = c.stack[:i] - } - - // If we've hit the end then return nil. - if len(c.stack) == 0 { - return nil, nil - } - - // Move down the stack to find the last element of the last leaf under this branch. - c.last() - k, v, flags := c.keyValue() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Seek moves the cursor to a given key and returns it. -// If the key does not exist then the next key is used. If no keys -// follow, a nil key is returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) { - k, v, flags := c.seek(seek) - - // If we ended up after the last element of a page then move to the next one. - if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() { - k, v, flags = c.next() - } - - if k == nil { - return nil, nil - } else if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Delete removes the current key/value under the cursor from the bucket. -// Delete fails if current key/value is a bucket or if the transaction is not writable. -func (c *Cursor) Delete() error { - if c.bucket.tx.db == nil { - return ErrTxClosed - } else if !c.bucket.Writable() { - return ErrTxNotWritable - } - - key, _, flags := c.keyValue() - // Return an error if current value is a bucket. - if (flags & bucketLeafFlag) != 0 { - return ErrIncompatibleValue - } - c.node().del(key) - - return nil -} - -// seek moves the cursor to a given key and returns it. -// If the key does not exist then the next key is used. -func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) { - _assert(c.bucket.tx.db != nil, "tx closed") - - // Start from root page/node and traverse to correct page. - c.stack = c.stack[:0] - c.search(seek, c.bucket.root) - - // If this is a bucket then return a nil value. - return c.keyValue() -} - -// first moves the cursor to the first leaf element under the last page in the stack. -func (c *Cursor) first() { - for { - // Exit when we hit a leaf page. - var ref = &c.stack[len(c.stack)-1] - if ref.isLeaf() { - break - } - - // Keep adding pages pointing to the first element to the stack. - var pgid pgid - if ref.node != nil { - pgid = ref.node.inodes[ref.index].pgid - } else { - pgid = ref.page.branchPageElement(uint16(ref.index)).pgid - } - p, n := c.bucket.pageNode(pgid) - c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) - } -} - -// last moves the cursor to the last leaf element under the last page in the stack. -func (c *Cursor) last() { - for { - // Exit when we hit a leaf page. - ref := &c.stack[len(c.stack)-1] - if ref.isLeaf() { - break - } - - // Keep adding pages pointing to the last element in the stack. - var pgid pgid - if ref.node != nil { - pgid = ref.node.inodes[ref.index].pgid - } else { - pgid = ref.page.branchPageElement(uint16(ref.index)).pgid - } - p, n := c.bucket.pageNode(pgid) - - var nextRef = elemRef{page: p, node: n} - nextRef.index = nextRef.count() - 1 - c.stack = append(c.stack, nextRef) - } -} - -// next moves to the next leaf element and returns the key and value. -// If the cursor is at the last leaf element then it stays there and returns nil. -func (c *Cursor) next() (key []byte, value []byte, flags uint32) { - for { - // Attempt to move over one element until we're successful. - // Move up the stack as we hit the end of each page in our stack. - var i int - for i = len(c.stack) - 1; i >= 0; i-- { - elem := &c.stack[i] - if elem.index < elem.count()-1 { - elem.index++ - break - } - } - - // If we've hit the root page then stop and return. This will leave the - // cursor on the last element of the last page. - if i == -1 { - return nil, nil, 0 - } - - // Otherwise start from where we left off in the stack and find the - // first element of the first leaf page. - c.stack = c.stack[:i+1] - c.first() - - // If this is an empty page then restart and move back up the stack. - // https://github.com/boltdb/bolt/issues/450 - if c.stack[len(c.stack)-1].count() == 0 { - continue - } - - return c.keyValue() - } -} - -// search recursively performs a binary search against a given page/node until it finds a given key. -func (c *Cursor) search(key []byte, pgid pgid) { - p, n := c.bucket.pageNode(pgid) - if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 { - panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags)) - } - e := elemRef{page: p, node: n} - c.stack = append(c.stack, e) - - // If we're on a leaf page/node then find the specific node. - if e.isLeaf() { - c.nsearch(key) - return - } - - if n != nil { - c.searchNode(key, n) - return - } - c.searchPage(key, p) -} - -func (c *Cursor) searchNode(key []byte, n *node) { - var exact bool - index := sort.Search(len(n.inodes), func(i int) bool { - // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. - // sort.Search() finds the lowest index where f() != -1 but we need the highest index. - ret := bytes.Compare(n.inodes[i].key, key) - if ret == 0 { - exact = true - } - return ret != -1 - }) - if !exact && index > 0 { - index-- - } - c.stack[len(c.stack)-1].index = index - - // Recursively search to the next page. - c.search(key, n.inodes[index].pgid) -} - -func (c *Cursor) searchPage(key []byte, p *page) { - // Binary search for the correct range. - inodes := p.branchPageElements() - - var exact bool - index := sort.Search(int(p.count), func(i int) bool { - // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. - // sort.Search() finds the lowest index where f() != -1 but we need the highest index. - ret := bytes.Compare(inodes[i].key(), key) - if ret == 0 { - exact = true - } - return ret != -1 - }) - if !exact && index > 0 { - index-- - } - c.stack[len(c.stack)-1].index = index - - // Recursively search to the next page. - c.search(key, inodes[index].pgid) -} - -// nsearch searches the leaf node on the top of the stack for a key. -func (c *Cursor) nsearch(key []byte) { - e := &c.stack[len(c.stack)-1] - p, n := e.page, e.node - - // If we have a node then search its inodes. - if n != nil { - index := sort.Search(len(n.inodes), func(i int) bool { - return bytes.Compare(n.inodes[i].key, key) != -1 - }) - e.index = index - return - } - - // If we have a page then search its leaf elements. - inodes := p.leafPageElements() - index := sort.Search(int(p.count), func(i int) bool { - return bytes.Compare(inodes[i].key(), key) != -1 - }) - e.index = index -} - -// keyValue returns the key and value of the current leaf element. -func (c *Cursor) keyValue() ([]byte, []byte, uint32) { - ref := &c.stack[len(c.stack)-1] - - // If the cursor is pointing to the end of page/node then return nil. - if ref.count() == 0 || ref.index >= ref.count() { - return nil, nil, 0 - } - - // Retrieve value from node. - if ref.node != nil { - inode := &ref.node.inodes[ref.index] - return inode.key, inode.value, inode.flags - } - - // Or retrieve value from page. - elem := ref.page.leafPageElement(uint16(ref.index)) - return elem.key(), elem.value(), elem.flags -} - -// node returns the node that the cursor is currently positioned on. -func (c *Cursor) node() *node { - _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack") - - // If the top of the stack is a leaf node then just return it. - if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() { - return ref.node - } - - // Start from root and traverse down the hierarchy. - var n = c.stack[0].node - if n == nil { - n = c.bucket.node(c.stack[0].page.id, nil) - } - for _, ref := range c.stack[:len(c.stack)-1] { - _assert(!n.isLeaf, "expected branch node") - n = n.childAt(int(ref.index)) - } - _assert(n.isLeaf, "expected leaf node") - return n -} - -// elemRef represents a reference to an element on a given page/node. -type elemRef struct { - page *page - node *node - index int -} - -// isLeaf returns whether the ref is pointing at a leaf page/node. -func (r *elemRef) isLeaf() bool { - if r.node != nil { - return r.node.isLeaf - } - return (r.page.flags & leafPageFlag) != 0 -} - -// count returns the number of inodes or page elements. -func (r *elemRef) count() int { - if r.node != nil { - return len(r.node.inodes) - } - return int(r.page.count) -} diff --git a/vendor/github.com/coreos/bbolt/cursor_test.go b/vendor/github.com/coreos/bbolt/cursor_test.go deleted file mode 100644 index 7b1ae19..0000000 --- a/vendor/github.com/coreos/bbolt/cursor_test.go +++ /dev/null @@ -1,817 +0,0 @@ -package bolt_test - -import ( - "bytes" - "encoding/binary" - "fmt" - "log" - "os" - "reflect" - "sort" - "testing" - "testing/quick" - - "github.com/coreos/bbolt" -) - -// Ensure that a cursor can return a reference to the bucket that created it. -func TestCursor_Bucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if cb := b.Cursor().Bucket(); !reflect.DeepEqual(cb, b) { - t.Fatal("cursor bucket mismatch") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can seek to the appropriate keys. -func TestCursor_Seek(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("0001")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte("0002")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("0003")); err != nil { - t.Fatal(err) - } - - if _, err := b.CreateBucket([]byte("bkt")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - - // Exact match should go to the key. - if k, v := c.Seek([]byte("bar")); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0002")) { - t.Fatalf("unexpected value: %v", v) - } - - // Inexact match should go to the next key. - if k, v := c.Seek([]byte("bas")); !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0003")) { - t.Fatalf("unexpected value: %v", v) - } - - // Low key should go to the first key. - if k, v := c.Seek([]byte("")); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0002")) { - t.Fatalf("unexpected value: %v", v) - } - - // High key should return no key. - if k, v := c.Seek([]byte("zzz")); k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - // Buckets should return their key but no value. - if k, v := c.Seek([]byte("bkt")); !bytes.Equal(k, []byte("bkt")) { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCursor_Delete(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - const count = 1000 - - // Insert every other key between 0 and $count. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < count; i += 1 { - k := make([]byte, 8) - binary.BigEndian.PutUint64(k, uint64(i)) - if err := b.Put(k, make([]byte, 100)); err != nil { - t.Fatal(err) - } - } - if _, err := b.CreateBucket([]byte("sub")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - bound := make([]byte, 8) - binary.BigEndian.PutUint64(bound, uint64(count/2)) - for key, _ := c.First(); bytes.Compare(key, bound) < 0; key, _ = c.Next() { - if err := c.Delete(); err != nil { - t.Fatal(err) - } - } - - c.Seek([]byte("sub")) - if err := c.Delete(); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("widgets")).Stats() - if stats.KeyN != count/2+1 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can seek to the appropriate keys when there are a -// large number of keys. This test also checks that seek will always move -// forward to the next key. -// -// Related: https://github.com/boltdb/bolt/pull/187 -func TestCursor_Seek_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var count = 10000 - - // Insert every other key between 0 and $count. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < count; i += 100 { - for j := i; j < i+100; j += 2 { - k := make([]byte, 8) - binary.BigEndian.PutUint64(k, uint64(j)) - if err := b.Put(k, make([]byte, 100)); err != nil { - t.Fatal(err) - } - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - for i := 0; i < count; i++ { - seek := make([]byte, 8) - binary.BigEndian.PutUint64(seek, uint64(i)) - - k, _ := c.Seek(seek) - - // The last seek is beyond the end of the the range so - // it should return nil. - if i == count-1 { - if k != nil { - t.Fatal("expected nil key") - } - continue - } - - // Otherwise we should seek to the exact key or the next key. - num := binary.BigEndian.Uint64(k) - if i%2 == 0 { - if num != uint64(i) { - t.Fatalf("unexpected num: %d", num) - } - } else { - if num != uint64(i+1) { - t.Fatalf("unexpected num: %d", num) - } - } - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a cursor can iterate over an empty bucket without error. -func TestCursor_EmptyBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - k, v := c.First() - if k != nil { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can reverse iterate over an empty bucket without error. -func TestCursor_EmptyBucketReverse(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - k, v := c.Last() - if k != nil { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can iterate over a single root with a couple elements. -func TestCursor_Iterate_Leaf(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte{}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte{0}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte{1}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - defer func() { _ = tx.Rollback() }() - - c := tx.Bucket([]byte("widgets")).Cursor() - - k, v := c.First() - if !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{1}) { - t.Fatalf("unexpected value: %v", v) - } - - k, v = c.Next() - if !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{}) { - t.Fatalf("unexpected value: %v", v) - } - - k, v = c.Next() - if !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{0}) { - t.Fatalf("unexpected value: %v", v) - } - - k, v = c.Next() - if k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - k, v = c.Next() - if k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can iterate in reverse over a single root with a couple elements. -func TestCursor_LeafRootReverse(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte{}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte{0}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte{1}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - - if k, v := c.Last(); !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{0}) { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Prev(); !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{}) { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Prev(); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{1}) { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Prev(); k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - if k, v := c.Prev(); k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can restart from the beginning. -func TestCursor_Restart(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte{}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte{}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - - if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } - if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } - - if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } - if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// Ensure that a cursor can skip over empty pages that have been deleted. -func TestCursor_First_EmptyPages(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create 1000 keys in the "widgets" bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < 1000; i++ { - if err := b.Put(u64tob(uint64(i)), []byte{}); err != nil { - t.Fatal(err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - - // Delete half the keys and then try to iterate. - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < 600; i++ { - if err := b.Delete(u64tob(uint64(i))); err != nil { - t.Fatal(err) - } - } - - c := b.Cursor() - var n int - for k, _ := c.First(); k != nil; k, _ = c.Next() { - n++ - } - if n != 400 { - t.Fatalf("unexpected key count: %d", n) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx can iterate over all elements in a bucket. -func TestCursor_QuickCheck(t *testing.T) { - f := func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - // Sort test data. - sort.Sort(items) - - // Iterate over all items and check consistency. - var index = 0 - tx, err = db.Begin(false) - if err != nil { - t.Fatal(err) - } - - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.First(); k != nil && index < len(items); k, v = c.Next() { - if !bytes.Equal(k, items[index].Key) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, items[index].Value) { - t.Fatalf("unexpected value: %v", v) - } - index++ - } - if len(items) != index { - t.Fatalf("unexpected item count: %v, expected %v", len(items), index) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - return true - } - if err := quick.Check(f, qconfig()); err != nil { - t.Error(err) - } -} - -// Ensure that a transaction can iterate over all elements in a bucket in reverse. -func TestCursor_QuickCheck_Reverse(t *testing.T) { - f := func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - // Sort test data. - sort.Sort(revtestdata(items)) - - // Iterate over all items and check consistency. - var index = 0 - tx, err = db.Begin(false) - if err != nil { - t.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.Last(); k != nil && index < len(items); k, v = c.Prev() { - if !bytes.Equal(k, items[index].Key) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, items[index].Value) { - t.Fatalf("unexpected value: %v", v) - } - index++ - } - if len(items) != index { - t.Fatalf("unexpected item count: %v, expected %v", len(items), index) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - return true - } - if err := quick.Check(f, qconfig()); err != nil { - t.Error(err) - } -} - -// Ensure that a Tx cursor can iterate over subbuckets. -func TestCursor_QuickCheck_BucketsOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("bar")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("baz")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - var names []string - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - names = append(names, string(k)) - if v != nil { - t.Fatalf("unexpected value: %v", v) - } - } - if !reflect.DeepEqual(names, []string{"bar", "baz", "foo"}) { - t.Fatalf("unexpected names: %+v", names) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can reverse iterate over subbuckets. -func TestCursor_QuickCheck_BucketsOnly_Reverse(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("bar")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("baz")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - var names []string - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.Last(); k != nil; k, v = c.Prev() { - names = append(names, string(k)) - if v != nil { - t.Fatalf("unexpected value: %v", v) - } - } - if !reflect.DeepEqual(names, []string{"foo", "baz", "bar"}) { - t.Fatalf("unexpected names: %+v", names) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func ExampleCursor() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a read-write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a new bucket. - b, err := tx.CreateBucket([]byte("animals")) - if err != nil { - return err - } - - // Insert data into a bucket. - if err := b.Put([]byte("dog"), []byte("fun")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("cat"), []byte("lame")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("liger"), []byte("awesome")); err != nil { - log.Fatal(err) - } - - // Create a cursor for iteration. - c := b.Cursor() - - // Iterate over items in sorted key order. This starts from the - // first key/value pair and updates the k/v variables to the - // next key/value on each iteration. - // - // The loop finishes at the end of the cursor when a nil key is returned. - for k, v := c.First(); k != nil; k, v = c.Next() { - fmt.Printf("A %s is %s.\n", k, v) - } - - return nil - }); err != nil { - log.Fatal(err) - } - - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // A cat is lame. - // A dog is fun. - // A liger is awesome. -} - -func ExampleCursor_reverse() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a read-write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a new bucket. - b, err := tx.CreateBucket([]byte("animals")) - if err != nil { - return err - } - - // Insert data into a bucket. - if err := b.Put([]byte("dog"), []byte("fun")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("cat"), []byte("lame")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("liger"), []byte("awesome")); err != nil { - log.Fatal(err) - } - - // Create a cursor for iteration. - c := b.Cursor() - - // Iterate over items in reverse sorted key order. This starts - // from the last key/value pair and updates the k/v variables to - // the previous key/value on each iteration. - // - // The loop finishes at the beginning of the cursor when a nil key - // is returned. - for k, v := c.Last(); k != nil; k, v = c.Prev() { - fmt.Printf("A %s is %s.\n", k, v) - } - - return nil - }); err != nil { - log.Fatal(err) - } - - // Close the database to release the file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // A liger is awesome. - // A dog is fun. - // A cat is lame. -} diff --git a/vendor/github.com/coreos/bbolt/db.go b/vendor/github.com/coreos/bbolt/db.go deleted file mode 100644 index ab97c60..0000000 --- a/vendor/github.com/coreos/bbolt/db.go +++ /dev/null @@ -1,1140 +0,0 @@ -package bolt - -import ( - "errors" - "fmt" - "hash/fnv" - "log" - "os" - "runtime" - "sort" - "sync" - "time" - "unsafe" -) - -// The largest step that can be taken when remapping the mmap. -const maxMmapStep = 1 << 30 // 1GB - -// The data file format version. -const version = 2 - -// Represents a marker value to indicate that a file is a Bolt DB. -const magic uint32 = 0xED0CDAED - -const pgidNoFreelist pgid = 0xffffffffffffffff - -// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when -// syncing changes to a file. This is required as some operating systems, -// such as OpenBSD, do not have a unified buffer cache (UBC) and writes -// must be synchronized using the msync(2) syscall. -const IgnoreNoSync = runtime.GOOS == "openbsd" - -// Default values if not set in a DB instance. -const ( - DefaultMaxBatchSize int = 1000 - DefaultMaxBatchDelay = 10 * time.Millisecond - DefaultAllocSize = 16 * 1024 * 1024 -) - -// default page size for db is set to the OS page size. -var defaultPageSize = os.Getpagesize() - -// The time elapsed between consecutive file locking attempts. -const flockRetryTimeout = 50 * time.Millisecond - -// DB represents a collection of buckets persisted to a file on disk. -// All data access is performed through transactions which can be obtained through the DB. -// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called. -type DB struct { - // When enabled, the database will perform a Check() after every commit. - // A panic is issued if the database is in an inconsistent state. This - // flag has a large performance impact so it should only be used for - // debugging purposes. - StrictMode bool - - // Setting the NoSync flag will cause the database to skip fsync() - // calls after each commit. This can be useful when bulk loading data - // into a database and you can restart the bulk load in the event of - // a system failure or database corruption. Do not set this flag for - // normal use. - // - // If the package global IgnoreNoSync constant is true, this value is - // ignored. See the comment on that constant for more details. - // - // THIS IS UNSAFE. PLEASE USE WITH CAUTION. - NoSync bool - - // When true, skips syncing freelist to disk. This improves the database - // write performance under normal operation, but requires a full database - // re-sync during recovery. - NoFreelistSync bool - - // When true, skips the truncate call when growing the database. - // Setting this to true is only safe on non-ext3/ext4 systems. - // Skipping truncation avoids preallocation of hard drive space and - // bypasses a truncate() and fsync() syscall on remapping. - // - // https://github.com/boltdb/bolt/issues/284 - NoGrowSync bool - - // If you want to read the entire database fast, you can set MmapFlag to - // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead. - MmapFlags int - - // MaxBatchSize is the maximum size of a batch. Default value is - // copied from DefaultMaxBatchSize in Open. - // - // If <=0, disables batching. - // - // Do not change concurrently with calls to Batch. - MaxBatchSize int - - // MaxBatchDelay is the maximum delay before a batch starts. - // Default value is copied from DefaultMaxBatchDelay in Open. - // - // If <=0, effectively disables batching. - // - // Do not change concurrently with calls to Batch. - MaxBatchDelay time.Duration - - // AllocSize is the amount of space allocated when the database - // needs to create new pages. This is done to amortize the cost - // of truncate() and fsync() when growing the data file. - AllocSize int - - path string - file *os.File - lockfile *os.File // windows only - dataref []byte // mmap'ed readonly, write throws SEGV - data *[maxMapSize]byte - datasz int - filesz int // current on disk file size - meta0 *meta - meta1 *meta - pageSize int - opened bool - rwtx *Tx - txs []*Tx - stats Stats - - freelist *freelist - freelistLoad sync.Once - - pagePool sync.Pool - - batchMu sync.Mutex - batch *batch - - rwlock sync.Mutex // Allows only one writer at a time. - metalock sync.Mutex // Protects meta page access. - mmaplock sync.RWMutex // Protects mmap access during remapping. - statlock sync.RWMutex // Protects stats access. - - ops struct { - writeAt func(b []byte, off int64) (n int, err error) - } - - // Read only mode. - // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately. - readOnly bool -} - -// Path returns the path to currently open database file. -func (db *DB) Path() string { - return db.path -} - -// GoString returns the Go string representation of the database. -func (db *DB) GoString() string { - return fmt.Sprintf("bolt.DB{path:%q}", db.path) -} - -// String returns the string representation of the database. -func (db *DB) String() string { - return fmt.Sprintf("DB<%q>", db.path) -} - -// Open creates and opens a database at the given path. -// If the file does not exist then it will be created automatically. -// Passing in nil options will cause Bolt to open the database with the default options. -func Open(path string, mode os.FileMode, options *Options) (*DB, error) { - db := &DB{ - opened: true, - } - // Set default options if no options are provided. - if options == nil { - options = DefaultOptions - } - db.NoSync = options.NoSync - db.NoGrowSync = options.NoGrowSync - db.MmapFlags = options.MmapFlags - db.NoFreelistSync = options.NoFreelistSync - - // Set default values for later DB operations. - db.MaxBatchSize = DefaultMaxBatchSize - db.MaxBatchDelay = DefaultMaxBatchDelay - db.AllocSize = DefaultAllocSize - - flag := os.O_RDWR - if options.ReadOnly { - flag = os.O_RDONLY - db.readOnly = true - } - - // Open data file and separate sync handler for metadata writes. - db.path = path - var err error - if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { - _ = db.close() - return nil, err - } - - // Lock file so that other processes using Bolt in read-write mode cannot - // use the database at the same time. This would cause corruption since - // the two processes would write meta pages and free pages separately. - // The database file is locked exclusively (only one process can grab the lock) - // if !options.ReadOnly. - // The database file is locked using the shared lock (more than one process may - // hold a lock at the same time) otherwise (options.ReadOnly is set). - if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil { - db.lockfile = nil // make 'unused' happy. TODO: rework locks - _ = db.close() - return nil, err - } - - // Default values for test hooks - db.ops.writeAt = db.file.WriteAt - - if db.pageSize = options.PageSize; db.pageSize == 0 { - // Set the default page size to the OS page size. - db.pageSize = defaultPageSize - } - - // Initialize the database if it doesn't exist. - if info, err := db.file.Stat(); err != nil { - _ = db.close() - return nil, err - } else if info.Size() == 0 { - // Initialize new files with meta pages. - if err := db.init(); err != nil { - // clean up file descriptor on initialization fail - _ = db.close() - return nil, err - } - } else { - // Read the first meta page to determine the page size. - var buf [0x1000]byte - // If we can't read the page size, but can read a page, assume - // it's the same as the OS or one given -- since that's how the - // page size was chosen in the first place. - // - // If the first page is invalid and this OS uses a different - // page size than what the database was created with then we - // are out of luck and cannot access the database. - // - // TODO: scan for next page - if bw, err := db.file.ReadAt(buf[:], 0); err == nil && bw == len(buf) { - if m := db.pageInBuffer(buf[:], 0).meta(); m.validate() == nil { - db.pageSize = int(m.pageSize) - } - } else { - _ = db.close() - return nil, ErrInvalid - } - } - - // Initialize page pool. - db.pagePool = sync.Pool{ - New: func() interface{} { - return make([]byte, db.pageSize) - }, - } - - // Memory map the data file. - if err := db.mmap(options.InitialMmapSize); err != nil { - _ = db.close() - return nil, err - } - - if db.readOnly { - return db, nil - } - - db.loadFreelist() - - // Flush freelist when transitioning from no sync to sync so - // NoFreelistSync unaware boltdb can open the db later. - if !db.NoFreelistSync && !db.hasSyncedFreelist() { - tx, err := db.Begin(true) - if tx != nil { - err = tx.Commit() - } - if err != nil { - _ = db.close() - return nil, err - } - } - - // Mark the database as opened and return. - return db, nil -} - -// loadFreelist reads the freelist if it is synced, or reconstructs it -// by scanning the DB if it is not synced. It assumes there are no -// concurrent accesses being made to the freelist. -func (db *DB) loadFreelist() { - db.freelistLoad.Do(func() { - db.freelist = newFreelist() - if !db.hasSyncedFreelist() { - // Reconstruct free list by scanning the DB. - db.freelist.readIDs(db.freepages()) - } else { - // Read free list from freelist page. - db.freelist.read(db.page(db.meta().freelist)) - } - db.stats.FreePageN = len(db.freelist.ids) - }) -} - -func (db *DB) hasSyncedFreelist() bool { - return db.meta().freelist != pgidNoFreelist -} - -// mmap opens the underlying memory-mapped file and initializes the meta references. -// minsz is the minimum size that the new mmap can be. -func (db *DB) mmap(minsz int) error { - db.mmaplock.Lock() - defer db.mmaplock.Unlock() - - info, err := db.file.Stat() - if err != nil { - return fmt.Errorf("mmap stat error: %s", err) - } else if int(info.Size()) < db.pageSize*2 { - return fmt.Errorf("file size too small") - } - - // Ensure the size is at least the minimum size. - var size = int(info.Size()) - if size < minsz { - size = minsz - } - size, err = db.mmapSize(size) - if err != nil { - return err - } - - // Dereference all mmap references before unmapping. - if db.rwtx != nil { - db.rwtx.root.dereference() - } - - // Unmap existing data before continuing. - if err := db.munmap(); err != nil { - return err - } - - // Memory-map the data file as a byte slice. - if err := mmap(db, size); err != nil { - return err - } - - // Save references to the meta pages. - db.meta0 = db.page(0).meta() - db.meta1 = db.page(1).meta() - - // Validate the meta pages. We only return an error if both meta pages fail - // validation, since meta0 failing validation means that it wasn't saved - // properly -- but we can recover using meta1. And vice-versa. - err0 := db.meta0.validate() - err1 := db.meta1.validate() - if err0 != nil && err1 != nil { - return err0 - } - - return nil -} - -// munmap unmaps the data file from memory. -func (db *DB) munmap() error { - if err := munmap(db); err != nil { - return fmt.Errorf("unmap error: " + err.Error()) - } - return nil -} - -// mmapSize determines the appropriate size for the mmap given the current size -// of the database. The minimum size is 32KB and doubles until it reaches 1GB. -// Returns an error if the new mmap size is greater than the max allowed. -func (db *DB) mmapSize(size int) (int, error) { - // Double the size from 32KB until 1GB. - for i := uint(15); i <= 30; i++ { - if size <= 1< maxMapSize { - return 0, fmt.Errorf("mmap too large") - } - - // If larger than 1GB then grow by 1GB at a time. - sz := int64(size) - if remainder := sz % int64(maxMmapStep); remainder > 0 { - sz += int64(maxMmapStep) - remainder - } - - // Ensure that the mmap size is a multiple of the page size. - // This should always be true since we're incrementing in MBs. - pageSize := int64(db.pageSize) - if (sz % pageSize) != 0 { - sz = ((sz / pageSize) + 1) * pageSize - } - - // If we've exceeded the max size then only grow up to the max size. - if sz > maxMapSize { - sz = maxMapSize - } - - return int(sz), nil -} - -// init creates a new database file and initializes its meta pages. -func (db *DB) init() error { - // Create two meta pages on a buffer. - buf := make([]byte, db.pageSize*4) - for i := 0; i < 2; i++ { - p := db.pageInBuffer(buf[:], pgid(i)) - p.id = pgid(i) - p.flags = metaPageFlag - - // Initialize the meta page. - m := p.meta() - m.magic = magic - m.version = version - m.pageSize = uint32(db.pageSize) - m.freelist = 2 - m.root = bucket{root: 3} - m.pgid = 4 - m.txid = txid(i) - m.checksum = m.sum64() - } - - // Write an empty freelist at page 3. - p := db.pageInBuffer(buf[:], pgid(2)) - p.id = pgid(2) - p.flags = freelistPageFlag - p.count = 0 - - // Write an empty leaf page at page 4. - p = db.pageInBuffer(buf[:], pgid(3)) - p.id = pgid(3) - p.flags = leafPageFlag - p.count = 0 - - // Write the buffer to our data file. - if _, err := db.ops.writeAt(buf, 0); err != nil { - return err - } - if err := fdatasync(db); err != nil { - return err - } - - return nil -} - -// Close releases all database resources. -// It will block waiting for any open transactions to finish -// before closing the database and returning. -func (db *DB) Close() error { - db.rwlock.Lock() - defer db.rwlock.Unlock() - - db.metalock.Lock() - defer db.metalock.Unlock() - - db.mmaplock.RLock() - defer db.mmaplock.RUnlock() - - return db.close() -} - -func (db *DB) close() error { - if !db.opened { - return nil - } - - db.opened = false - - db.freelist = nil - - // Clear ops. - db.ops.writeAt = nil - - // Close the mmap. - if err := db.munmap(); err != nil { - return err - } - - // Close file handles. - if db.file != nil { - // No need to unlock read-only file. - if !db.readOnly { - // Unlock the file. - if err := funlock(db); err != nil { - log.Printf("bolt.Close(): funlock error: %s", err) - } - } - - // Close the file descriptor. - if err := db.file.Close(); err != nil { - return fmt.Errorf("db file close: %s", err) - } - db.file = nil - } - - db.path = "" - return nil -} - -// Begin starts a new transaction. -// Multiple read-only transactions can be used concurrently but only one -// write transaction can be used at a time. Starting multiple write transactions -// will cause the calls to block and be serialized until the current write -// transaction finishes. -// -// Transactions should not be dependent on one another. Opening a read -// transaction and a write transaction in the same goroutine can cause the -// writer to deadlock because the database periodically needs to re-mmap itself -// as it grows and it cannot do that while a read transaction is open. -// -// If a long running read transaction (for example, a snapshot transaction) is -// needed, you might want to set DB.InitialMmapSize to a large enough value -// to avoid potential blocking of write transaction. -// -// IMPORTANT: You must close read-only transactions after you are finished or -// else the database will not reclaim old pages. -func (db *DB) Begin(writable bool) (*Tx, error) { - if writable { - return db.beginRWTx() - } - return db.beginTx() -} - -func (db *DB) beginTx() (*Tx, error) { - // Lock the meta pages while we initialize the transaction. We obtain - // the meta lock before the mmap lock because that's the order that the - // write transaction will obtain them. - db.metalock.Lock() - - // Obtain a read-only lock on the mmap. When the mmap is remapped it will - // obtain a write lock so all transactions must finish before it can be - // remapped. - db.mmaplock.RLock() - - // Exit if the database is not open yet. - if !db.opened { - db.mmaplock.RUnlock() - db.metalock.Unlock() - return nil, ErrDatabaseNotOpen - } - - // Create a transaction associated with the database. - t := &Tx{} - t.init(db) - - // Keep track of transaction until it closes. - db.txs = append(db.txs, t) - n := len(db.txs) - - // Unlock the meta pages. - db.metalock.Unlock() - - // Update the transaction stats. - db.statlock.Lock() - db.stats.TxN++ - db.stats.OpenTxN = n - db.statlock.Unlock() - - return t, nil -} - -func (db *DB) beginRWTx() (*Tx, error) { - // If the database was opened with Options.ReadOnly, return an error. - if db.readOnly { - return nil, ErrDatabaseReadOnly - } - - // Obtain writer lock. This is released by the transaction when it closes. - // This enforces only one writer transaction at a time. - db.rwlock.Lock() - - // Once we have the writer lock then we can lock the meta pages so that - // we can set up the transaction. - db.metalock.Lock() - defer db.metalock.Unlock() - - // Exit if the database is not open yet. - if !db.opened { - db.rwlock.Unlock() - return nil, ErrDatabaseNotOpen - } - - // Create a transaction associated with the database. - t := &Tx{writable: true} - t.init(db) - db.rwtx = t - db.freePages() - return t, nil -} - -// freePages releases any pages associated with closed read-only transactions. -func (db *DB) freePages() { - // Free all pending pages prior to earliest open transaction. - sort.Sort(txsById(db.txs)) - minid := txid(0xFFFFFFFFFFFFFFFF) - if len(db.txs) > 0 { - minid = db.txs[0].meta.txid - } - if minid > 0 { - db.freelist.release(minid - 1) - } - // Release unused txid extents. - for _, t := range db.txs { - db.freelist.releaseRange(minid, t.meta.txid-1) - minid = t.meta.txid + 1 - } - db.freelist.releaseRange(minid, txid(0xFFFFFFFFFFFFFFFF)) - // Any page both allocated and freed in an extent is safe to release. -} - -type txsById []*Tx - -func (t txsById) Len() int { return len(t) } -func (t txsById) Swap(i, j int) { t[i], t[j] = t[j], t[i] } -func (t txsById) Less(i, j int) bool { return t[i].meta.txid < t[j].meta.txid } - -// removeTx removes a transaction from the database. -func (db *DB) removeTx(tx *Tx) { - // Release the read lock on the mmap. - db.mmaplock.RUnlock() - - // Use the meta lock to restrict access to the DB object. - db.metalock.Lock() - - // Remove the transaction. - for i, t := range db.txs { - if t == tx { - last := len(db.txs) - 1 - db.txs[i] = db.txs[last] - db.txs[last] = nil - db.txs = db.txs[:last] - break - } - } - n := len(db.txs) - - // Unlock the meta pages. - db.metalock.Unlock() - - // Merge statistics. - db.statlock.Lock() - db.stats.OpenTxN = n - db.stats.TxStats.add(&tx.stats) - db.statlock.Unlock() -} - -// Update executes a function within the context of a read-write managed transaction. -// If no error is returned from the function then the transaction is committed. -// If an error is returned then the entire transaction is rolled back. -// Any error that is returned from the function or returned from the commit is -// returned from the Update() method. -// -// Attempting to manually commit or rollback within the function will cause a panic. -func (db *DB) Update(fn func(*Tx) error) error { - t, err := db.Begin(true) - if err != nil { - return err - } - - // Make sure the transaction rolls back in the event of a panic. - defer func() { - if t.db != nil { - t.rollback() - } - }() - - // Mark as a managed tx so that the inner function cannot manually commit. - t.managed = true - - // If an error is returned from the function then rollback and return error. - err = fn(t) - t.managed = false - if err != nil { - _ = t.Rollback() - return err - } - - return t.Commit() -} - -// View executes a function within the context of a managed read-only transaction. -// Any error that is returned from the function is returned from the View() method. -// -// Attempting to manually rollback within the function will cause a panic. -func (db *DB) View(fn func(*Tx) error) error { - t, err := db.Begin(false) - if err != nil { - return err - } - - // Make sure the transaction rolls back in the event of a panic. - defer func() { - if t.db != nil { - t.rollback() - } - }() - - // Mark as a managed tx so that the inner function cannot manually rollback. - t.managed = true - - // If an error is returned from the function then pass it through. - err = fn(t) - t.managed = false - if err != nil { - _ = t.Rollback() - return err - } - - return t.Rollback() -} - -// Batch calls fn as part of a batch. It behaves similar to Update, -// except: -// -// 1. concurrent Batch calls can be combined into a single Bolt -// transaction. -// -// 2. the function passed to Batch may be called multiple times, -// regardless of whether it returns error or not. -// -// This means that Batch function side effects must be idempotent and -// take permanent effect only after a successful return is seen in -// caller. -// -// The maximum batch size and delay can be adjusted with DB.MaxBatchSize -// and DB.MaxBatchDelay, respectively. -// -// Batch is only useful when there are multiple goroutines calling it. -func (db *DB) Batch(fn func(*Tx) error) error { - errCh := make(chan error, 1) - - db.batchMu.Lock() - if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) { - // There is no existing batch, or the existing batch is full; start a new one. - db.batch = &batch{ - db: db, - } - db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger) - } - db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh}) - if len(db.batch.calls) >= db.MaxBatchSize { - // wake up batch, it's ready to run - go db.batch.trigger() - } - db.batchMu.Unlock() - - err := <-errCh - if err == trySolo { - err = db.Update(fn) - } - return err -} - -type call struct { - fn func(*Tx) error - err chan<- error -} - -type batch struct { - db *DB - timer *time.Timer - start sync.Once - calls []call -} - -// trigger runs the batch if it hasn't already been run. -func (b *batch) trigger() { - b.start.Do(b.run) -} - -// run performs the transactions in the batch and communicates results -// back to DB.Batch. -func (b *batch) run() { - b.db.batchMu.Lock() - b.timer.Stop() - // Make sure no new work is added to this batch, but don't break - // other batches. - if b.db.batch == b { - b.db.batch = nil - } - b.db.batchMu.Unlock() - -retry: - for len(b.calls) > 0 { - var failIdx = -1 - err := b.db.Update(func(tx *Tx) error { - for i, c := range b.calls { - if err := safelyCall(c.fn, tx); err != nil { - failIdx = i - return err - } - } - return nil - }) - - if failIdx >= 0 { - // take the failing transaction out of the batch. it's - // safe to shorten b.calls here because db.batch no longer - // points to us, and we hold the mutex anyway. - c := b.calls[failIdx] - b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] - // tell the submitter re-run it solo, continue with the rest of the batch - c.err <- trySolo - continue retry - } - - // pass success, or bolt internal errors, to all callers - for _, c := range b.calls { - c.err <- err - } - break retry - } -} - -// trySolo is a special sentinel error value used for signaling that a -// transaction function should be re-run. It should never be seen by -// callers. -var trySolo = errors.New("batch function returned an error and should be re-run solo") - -type panicked struct { - reason interface{} -} - -func (p panicked) Error() string { - if err, ok := p.reason.(error); ok { - return err.Error() - } - return fmt.Sprintf("panic: %v", p.reason) -} - -func safelyCall(fn func(*Tx) error, tx *Tx) (err error) { - defer func() { - if p := recover(); p != nil { - err = panicked{p} - } - }() - return fn(tx) -} - -// Sync executes fdatasync() against the database file handle. -// -// This is not necessary under normal operation, however, if you use NoSync -// then it allows you to force the database file to sync against the disk. -func (db *DB) Sync() error { return fdatasync(db) } - -// Stats retrieves ongoing performance stats for the database. -// This is only updated when a transaction closes. -func (db *DB) Stats() Stats { - db.statlock.RLock() - defer db.statlock.RUnlock() - return db.stats -} - -// This is for internal access to the raw data bytes from the C cursor, use -// carefully, or not at all. -func (db *DB) Info() *Info { - return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} -} - -// page retrieves a page reference from the mmap based on the current page size. -func (db *DB) page(id pgid) *page { - pos := id * pgid(db.pageSize) - return (*page)(unsafe.Pointer(&db.data[pos])) -} - -// pageInBuffer retrieves a page reference from a given byte array based on the current page size. -func (db *DB) pageInBuffer(b []byte, id pgid) *page { - return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) -} - -// meta retrieves the current meta page reference. -func (db *DB) meta() *meta { - // We have to return the meta with the highest txid which doesn't fail - // validation. Otherwise, we can cause errors when in fact the database is - // in a consistent state. metaA is the one with the higher txid. - metaA := db.meta0 - metaB := db.meta1 - if db.meta1.txid > db.meta0.txid { - metaA = db.meta1 - metaB = db.meta0 - } - - // Use higher meta page if valid. Otherwise fallback to previous, if valid. - if err := metaA.validate(); err == nil { - return metaA - } else if err := metaB.validate(); err == nil { - return metaB - } - - // This should never be reached, because both meta1 and meta0 were validated - // on mmap() and we do fsync() on every write. - panic("bolt.DB.meta(): invalid meta pages") -} - -// allocate returns a contiguous block of memory starting at a given page. -func (db *DB) allocate(txid txid, count int) (*page, error) { - // Allocate a temporary buffer for the page. - var buf []byte - if count == 1 { - buf = db.pagePool.Get().([]byte) - } else { - buf = make([]byte, count*db.pageSize) - } - p := (*page)(unsafe.Pointer(&buf[0])) - p.overflow = uint32(count - 1) - - // Use pages from the freelist if they are available. - if p.id = db.freelist.allocate(txid, count); p.id != 0 { - return p, nil - } - - // Resize mmap() if we're at the end. - p.id = db.rwtx.meta.pgid - var minsz = int((p.id+pgid(count))+1) * db.pageSize - if minsz >= db.datasz { - if err := db.mmap(minsz); err != nil { - return nil, fmt.Errorf("mmap allocate error: %s", err) - } - } - - // Move the page id high water mark. - db.rwtx.meta.pgid += pgid(count) - - return p, nil -} - -// grow grows the size of the database to the given sz. -func (db *DB) grow(sz int) error { - // Ignore if the new size is less than available file size. - if sz <= db.filesz { - return nil - } - - // If the data is smaller than the alloc size then only allocate what's needed. - // Once it goes over the allocation size then allocate in chunks. - if db.datasz < db.AllocSize { - sz = db.datasz - } else { - sz += db.AllocSize - } - - // Truncate and fsync to ensure file size metadata is flushed. - // https://github.com/boltdb/bolt/issues/284 - if !db.NoGrowSync && !db.readOnly { - if runtime.GOOS != "windows" { - if err := db.file.Truncate(int64(sz)); err != nil { - return fmt.Errorf("file resize error: %s", err) - } - } - if err := db.file.Sync(); err != nil { - return fmt.Errorf("file sync error: %s", err) - } - } - - db.filesz = sz - return nil -} - -func (db *DB) IsReadOnly() bool { - return db.readOnly -} - -func (db *DB) freepages() []pgid { - tx, err := db.beginTx() - defer func() { - err = tx.Rollback() - if err != nil { - panic("freepages: failed to rollback tx") - } - }() - if err != nil { - panic("freepages: failed to open read only tx") - } - - reachable := make(map[pgid]*page) - nofreed := make(map[pgid]bool) - ech := make(chan error) - go func() { - for e := range ech { - panic(fmt.Sprintf("freepages: failed to get all reachable pages (%v)", e)) - } - }() - tx.checkBucket(&tx.root, reachable, nofreed, ech) - close(ech) - - var fids []pgid - for i := pgid(2); i < db.meta().pgid; i++ { - if _, ok := reachable[i]; !ok { - fids = append(fids, i) - } - } - return fids -} - -// Options represents the options that can be set when opening a database. -type Options struct { - // Timeout is the amount of time to wait to obtain a file lock. - // When set to zero it will wait indefinitely. This option is only - // available on Darwin and Linux. - Timeout time.Duration - - // Sets the DB.NoGrowSync flag before memory mapping the file. - NoGrowSync bool - - // Do not sync freelist to disk. This improves the database write performance - // under normal operation, but requires a full database re-sync during recovery. - NoFreelistSync bool - - // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to - // grab a shared lock (UNIX). - ReadOnly bool - - // Sets the DB.MmapFlags flag before memory mapping the file. - MmapFlags int - - // InitialMmapSize is the initial mmap size of the database - // in bytes. Read transactions won't block write transaction - // if the InitialMmapSize is large enough to hold database mmap - // size. (See DB.Begin for more information) - // - // If <=0, the initial map size is 0. - // If initialMmapSize is smaller than the previous database size, - // it takes no effect. - InitialMmapSize int - - // PageSize overrides the default OS page size. - PageSize int - - // NoSync sets the initial value of DB.NoSync. Normally this can just be - // set directly on the DB itself when returned from Open(), but this option - // is useful in APIs which expose Options but not the underlying DB. - NoSync bool -} - -// DefaultOptions represent the options used if nil options are passed into Open(). -// No timeout is used which will cause Bolt to wait indefinitely for a lock. -var DefaultOptions = &Options{ - Timeout: 0, - NoGrowSync: false, -} - -// Stats represents statistics about the database. -type Stats struct { - // Freelist stats - FreePageN int // total number of free pages on the freelist - PendingPageN int // total number of pending pages on the freelist - FreeAlloc int // total bytes allocated in free pages - FreelistInuse int // total bytes used by the freelist - - // Transaction stats - TxN int // total number of started read transactions - OpenTxN int // number of currently open read transactions - - TxStats TxStats // global, ongoing stats. -} - -// Sub calculates and returns the difference between two sets of database stats. -// This is useful when obtaining stats at two different points and time and -// you need the performance counters that occurred within that time span. -func (s *Stats) Sub(other *Stats) Stats { - if other == nil { - return *s - } - var diff Stats - diff.FreePageN = s.FreePageN - diff.PendingPageN = s.PendingPageN - diff.FreeAlloc = s.FreeAlloc - diff.FreelistInuse = s.FreelistInuse - diff.TxN = s.TxN - other.TxN - diff.TxStats = s.TxStats.Sub(&other.TxStats) - return diff -} - -type Info struct { - Data uintptr - PageSize int -} - -type meta struct { - magic uint32 - version uint32 - pageSize uint32 - flags uint32 - root bucket - freelist pgid - pgid pgid - txid txid - checksum uint64 -} - -// validate checks the marker bytes and version of the meta page to ensure it matches this binary. -func (m *meta) validate() error { - if m.magic != magic { - return ErrInvalid - } else if m.version != version { - return ErrVersionMismatch - } else if m.checksum != 0 && m.checksum != m.sum64() { - return ErrChecksum - } - return nil -} - -// copy copies one meta object to another. -func (m *meta) copy(dest *meta) { - *dest = *m -} - -// write writes the meta onto a page. -func (m *meta) write(p *page) { - if m.root.root >= m.pgid { - panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) - } else if m.freelist >= m.pgid && m.freelist != pgidNoFreelist { - // TODO: reject pgidNoFreeList if !NoFreelistSync - panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) - } - - // Page id is either going to be 0 or 1 which we can determine by the transaction ID. - p.id = pgid(m.txid % 2) - p.flags |= metaPageFlag - - // Calculate the checksum. - m.checksum = m.sum64() - - m.copy(p.meta()) -} - -// generates the checksum for the meta. -func (m *meta) sum64() uint64 { - var h = fnv.New64a() - _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) - return h.Sum64() -} - -// _assert will panic with a given formatted message if the given condition is false. -func _assert(condition bool, msg string, v ...interface{}) { - if !condition { - panic(fmt.Sprintf("assertion failed: "+msg, v...)) - } -} diff --git a/vendor/github.com/coreos/bbolt/db_test.go b/vendor/github.com/coreos/bbolt/db_test.go deleted file mode 100644 index e3a58c3..0000000 --- a/vendor/github.com/coreos/bbolt/db_test.go +++ /dev/null @@ -1,1721 +0,0 @@ -package bolt_test - -import ( - "bytes" - "encoding/binary" - "errors" - "flag" - "fmt" - "hash/fnv" - "io/ioutil" - "log" - "math/rand" - "os" - "path/filepath" - "regexp" - "sync" - "testing" - "time" - "unsafe" - - "github.com/coreos/bbolt" -) - -var statsFlag = flag.Bool("stats", false, "show performance stats") - -// pageSize is the size of one page in the data file. -const pageSize = 4096 - -// pageHeaderSize is the size of a page header. -const pageHeaderSize = 16 - -// meta represents a simplified version of a database meta page for testing. -type meta struct { - magic uint32 - version uint32 - _ uint32 - _ uint32 - _ [16]byte - _ uint64 - pgid uint64 - _ uint64 - checksum uint64 -} - -// Ensure that a database can be opened without error. -func TestOpen(t *testing.T) { - path := tempfile() - defer os.RemoveAll(path) - - db, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } else if db == nil { - t.Fatal("expected db") - } - - if s := db.Path(); s != path { - t.Fatalf("unexpected path: %s", s) - } - - if err := db.Close(); err != nil { - t.Fatal(err) - } -} - -// Ensure that opening a database with a blank path returns an error. -func TestOpen_ErrPathRequired(t *testing.T) { - _, err := bolt.Open("", 0666, nil) - if err == nil { - t.Fatalf("expected error") - } -} - -// Ensure that opening a database with a bad path returns an error. -func TestOpen_ErrNotExists(t *testing.T) { - _, err := bolt.Open(filepath.Join(tempfile(), "bad-path"), 0666, nil) - if err == nil { - t.Fatal("expected error") - } -} - -// Ensure that opening a file that is not a Bolt database returns ErrInvalid. -func TestOpen_ErrInvalid(t *testing.T) { - path := tempfile() - defer os.RemoveAll(path) - - f, err := os.Create(path) - if err != nil { - t.Fatal(err) - } - if _, err := fmt.Fprintln(f, "this is not a bolt database"); err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - - if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrInvalid { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that opening a file with two invalid versions returns ErrVersionMismatch. -func TestOpen_ErrVersionMismatch(t *testing.T) { - if pageSize != os.Getpagesize() { - t.Skip("page size mismatch") - } - - // Create empty database. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - // Close database. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - // Read data file. - buf, err := ioutil.ReadFile(path) - if err != nil { - t.Fatal(err) - } - - // Rewrite meta pages. - meta0 := (*meta)(unsafe.Pointer(&buf[pageHeaderSize])) - meta0.version++ - meta1 := (*meta)(unsafe.Pointer(&buf[pageSize+pageHeaderSize])) - meta1.version++ - if err := ioutil.WriteFile(path, buf, 0666); err != nil { - t.Fatal(err) - } - - // Reopen data file. - if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrVersionMismatch { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that opening a file with two invalid checksums returns ErrChecksum. -func TestOpen_ErrChecksum(t *testing.T) { - if pageSize != os.Getpagesize() { - t.Skip("page size mismatch") - } - - // Create empty database. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - // Close database. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - // Read data file. - buf, err := ioutil.ReadFile(path) - if err != nil { - t.Fatal(err) - } - - // Rewrite meta pages. - meta0 := (*meta)(unsafe.Pointer(&buf[pageHeaderSize])) - meta0.pgid++ - meta1 := (*meta)(unsafe.Pointer(&buf[pageSize+pageHeaderSize])) - meta1.pgid++ - if err := ioutil.WriteFile(path, buf, 0666); err != nil { - t.Fatal(err) - } - - // Reopen data file. - if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrChecksum { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that opening a database does not increase its size. -// https://github.com/boltdb/bolt/issues/291 -func TestOpen_Size(t *testing.T) { - // Open a data file. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - pagesize := db.Info().PageSize - - // Insert until we get above the minimum 4MB size. - if err := db.Update(func(tx *bolt.Tx) error { - b, _ := tx.CreateBucketIfNotExists([]byte("data")) - for i := 0; i < 10000; i++ { - if err := b.Put([]byte(fmt.Sprintf("%04d", i)), make([]byte, 1000)); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Close database and grab the size. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - sz := fileSize(path) - if sz == 0 { - t.Fatalf("unexpected new file size: %d", sz) - } - - // Reopen database, update, and check size again. - db0, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db0.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("data")).Put([]byte{0}, []byte{0}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - if err := db0.Close(); err != nil { - t.Fatal(err) - } - newSz := fileSize(path) - if newSz == 0 { - t.Fatalf("unexpected new file size: %d", newSz) - } - - // Compare the original size with the new size. - // db size might increase by a few page sizes due to the new small update. - if sz < newSz-5*int64(pagesize) { - t.Fatalf("unexpected file growth: %d => %d", sz, newSz) - } -} - -// Ensure that opening a database beyond the max step size does not increase its size. -// https://github.com/boltdb/bolt/issues/303 -func TestOpen_Size_Large(t *testing.T) { - if testing.Short() { - t.Skip("short mode") - } - - // Open a data file. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - pagesize := db.Info().PageSize - - // Insert until we get above the minimum 4MB size. - var index uint64 - for i := 0; i < 10000; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - b, _ := tx.CreateBucketIfNotExists([]byte("data")) - for j := 0; j < 1000; j++ { - if err := b.Put(u64tob(index), make([]byte, 50)); err != nil { - t.Fatal(err) - } - index++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - // Close database and grab the size. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - sz := fileSize(path) - if sz == 0 { - t.Fatalf("unexpected new file size: %d", sz) - } else if sz < (1 << 30) { - t.Fatalf("expected larger initial size: %d", sz) - } - - // Reopen database, update, and check size again. - db0, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db0.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("data")).Put([]byte{0}, []byte{0}) - }); err != nil { - t.Fatal(err) - } - if err := db0.Close(); err != nil { - t.Fatal(err) - } - - newSz := fileSize(path) - if newSz == 0 { - t.Fatalf("unexpected new file size: %d", newSz) - } - - // Compare the original size with the new size. - // db size might increase by a few page sizes due to the new small update. - if sz < newSz-5*int64(pagesize) { - t.Fatalf("unexpected file growth: %d => %d", sz, newSz) - } -} - -// Ensure that a re-opened database is consistent. -func TestOpen_Check(t *testing.T) { - path := tempfile() - defer os.RemoveAll(path) - - db, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err = db.View(func(tx *bolt.Tx) error { return <-tx.Check() }); err != nil { - t.Fatal(err) - } - if err = db.Close(); err != nil { - t.Fatal(err) - } - - db, err = bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db.View(func(tx *bolt.Tx) error { return <-tx.Check() }); err != nil { - t.Fatal(err) - } - if err := db.Close(); err != nil { - t.Fatal(err) - } -} - -// Ensure that write errors to the meta file handler during initialization are returned. -func TestOpen_MetaInitWriteError(t *testing.T) { - t.Skip("pending") -} - -// Ensure that a database that is too small returns an error. -func TestOpen_FileTooSmall(t *testing.T) { - path := tempfile() - defer os.RemoveAll(path) - - db, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - pageSize := int64(db.Info().PageSize) - if err = db.Close(); err != nil { - t.Fatal(err) - } - - // corrupt the database - if err = os.Truncate(path, pageSize); err != nil { - t.Fatal(err) - } - - db, err = bolt.Open(path, 0666, nil) - if err == nil || err.Error() != "file size too small" { - t.Fatalf("unexpected error: %s", err) - } -} - -// TestDB_Open_InitialMmapSize tests if having InitialMmapSize large enough -// to hold data from concurrent write transaction resolves the issue that -// read transaction blocks the write transaction and causes deadlock. -// This is a very hacky test since the mmap size is not exposed. -func TestDB_Open_InitialMmapSize(t *testing.T) { - path := tempfile() - defer os.Remove(path) - - initMmapSize := 1 << 30 // 1GB - testWriteSize := 1 << 27 // 134MB - - db, err := bolt.Open(path, 0666, &bolt.Options{InitialMmapSize: initMmapSize}) - if err != nil { - t.Fatal(err) - } - - // create a long-running read transaction - // that never gets closed while writing - rtx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - - // create a write transaction - wtx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := wtx.CreateBucket([]byte("test")) - if err != nil { - t.Fatal(err) - } - - // and commit a large write - err = b.Put([]byte("foo"), make([]byte, testWriteSize)) - if err != nil { - t.Fatal(err) - } - - done := make(chan struct{}) - - go func() { - if err := wtx.Commit(); err != nil { - t.Fatal(err) - } - done <- struct{}{} - }() - - select { - case <-time.After(5 * time.Second): - t.Errorf("unexpected that the reader blocks writer") - case <-done: - } - - if err := rtx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// TestDB_Open_ReadOnly checks a database in read only mode can read but not write. -func TestDB_Open_ReadOnly(t *testing.T) { - // Create a writable db, write k-v and close it. - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - f := db.f - o := &bolt.Options{ReadOnly: true} - readOnlyDB, err := bolt.Open(f, 0666, o) - if err != nil { - panic(err) - } - - if !readOnlyDB.IsReadOnly() { - t.Fatal("expect db in read only mode") - } - - // Read from a read-only transaction. - if err := readOnlyDB.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - if !bytes.Equal(value, []byte("bar")) { - t.Fatal("expect value 'bar', got", value) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Can't launch read-write transaction. - if _, err := readOnlyDB.Begin(true); err != bolt.ErrDatabaseReadOnly { - t.Fatalf("unexpected error: %s", err) - } - - if err := readOnlyDB.Close(); err != nil { - t.Fatal(err) - } -} - -// TestOpen_BigPage checks the database uses bigger pages when -// changing PageSize. -func TestOpen_BigPage(t *testing.T) { - pageSize := os.Getpagesize() - - db1 := MustOpenWithOption(&bolt.Options{PageSize: pageSize * 2}) - defer db1.MustClose() - - db2 := MustOpenWithOption(&bolt.Options{PageSize: pageSize * 4}) - defer db2.MustClose() - - if db1sz, db2sz := fileSize(db1.f), fileSize(db2.f); db1sz >= db2sz { - t.Errorf("expected %d < %d", db1sz, db2sz) - } -} - -// TestOpen_RecoverFreeList tests opening the DB with free-list -// write-out after no free list sync will recover the free list -// and write it out. -func TestOpen_RecoverFreeList(t *testing.T) { - db := MustOpenWithOption(&bolt.Options{NoFreelistSync: true}) - defer db.MustClose() - - // Write some pages. - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - wbuf := make([]byte, 8192) - for i := 0; i < 100; i++ { - s := fmt.Sprintf("%d", i) - b, err := tx.CreateBucket([]byte(s)) - if err != nil { - t.Fatal(err) - } - if err = b.Put([]byte(s), wbuf); err != nil { - t.Fatal(err) - } - } - if err = tx.Commit(); err != nil { - t.Fatal(err) - } - - // Generate free pages. - if tx, err = db.Begin(true); err != nil { - t.Fatal(err) - } - for i := 0; i < 50; i++ { - s := fmt.Sprintf("%d", i) - b := tx.Bucket([]byte(s)) - if b == nil { - t.Fatal(err) - } - if err := b.Delete([]byte(s)); err != nil { - t.Fatal(err) - } - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - // Record freelist count from opening with NoFreelistSync. - db.MustReopen() - freepages := db.Stats().FreePageN - if freepages == 0 { - t.Fatalf("no free pages on NoFreelistSync reopen") - } - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - // Check free page count is reconstructed when opened with freelist sync. - db.o = &bolt.Options{} - db.MustReopen() - // One less free page for syncing the free list on open. - freepages-- - if fp := db.Stats().FreePageN; fp < freepages { - t.Fatalf("closed with %d free pages, opened with %d", freepages, fp) - } -} - -// Ensure that a database cannot open a transaction when it's not open. -func TestDB_Begin_ErrDatabaseNotOpen(t *testing.T) { - var db bolt.DB - if _, err := db.Begin(false); err != bolt.ErrDatabaseNotOpen { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that a read-write transaction can be retrieved. -func TestDB_BeginRW(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } else if tx == nil { - t.Fatal("expected tx") - } - - if tx.DB() != db.DB { - t.Fatal("unexpected tx database") - } else if !tx.Writable() { - t.Fatal("expected writable tx") - } - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } -} - -// TestDB_Concurrent_WriteTo checks that issuing WriteTo operations concurrently -// with commits does not produce corrupted db files. -func TestDB_Concurrent_WriteTo(t *testing.T) { - o := &bolt.Options{NoFreelistSync: false} - db := MustOpenWithOption(o) - defer db.MustClose() - - var wg sync.WaitGroup - wtxs, rtxs := 5, 5 - wg.Add(wtxs * rtxs) - f := func(tx *bolt.Tx) { - defer wg.Done() - f, err := ioutil.TempFile("", "bolt-") - if err != nil { - panic(err) - } - time.Sleep(time.Duration(rand.Intn(20)+1) * time.Millisecond) - tx.WriteTo(f) - tx.Rollback() - f.Close() - snap := &DB{nil, f.Name(), o} - snap.MustReopen() - defer snap.MustClose() - snap.MustCheck() - } - - tx1, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - if _, err := tx1.CreateBucket([]byte("abc")); err != nil { - t.Fatal(err) - } - if err := tx1.Commit(); err != nil { - t.Fatal(err) - } - - for i := 0; i < wtxs; i++ { - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - if err := tx.Bucket([]byte("abc")).Put([]byte{0}, []byte{0}); err != nil { - t.Fatal(err) - } - for j := 0; j < rtxs; j++ { - rtx, rerr := db.Begin(false) - if rerr != nil { - t.Fatal(rerr) - } - go f(rtx) - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - } - wg.Wait() -} - -// Ensure that opening a transaction while the DB is closed returns an error. -func TestDB_BeginRW_Closed(t *testing.T) { - var db bolt.DB - if _, err := db.Begin(true); err != bolt.ErrDatabaseNotOpen { - t.Fatalf("unexpected error: %s", err) - } -} - -func TestDB_Close_PendingTx_RW(t *testing.T) { testDB_Close_PendingTx(t, true) } -func TestDB_Close_PendingTx_RO(t *testing.T) { testDB_Close_PendingTx(t, false) } - -// Ensure that a database cannot close while transactions are open. -func testDB_Close_PendingTx(t *testing.T, writable bool) { - db := MustOpenDB() - defer db.MustClose() - - // Start transaction. - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - // Open update in separate goroutine. - done := make(chan struct{}) - go func() { - if err := db.Close(); err != nil { - t.Fatal(err) - } - close(done) - }() - - // Ensure database hasn't closed. - time.Sleep(100 * time.Millisecond) - select { - case <-done: - t.Fatal("database closed too early") - default: - } - - // Commit transaction. - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - // Ensure database closed now. - time.Sleep(100 * time.Millisecond) - select { - case <-done: - default: - t.Fatal("database did not close") - } -} - -// Ensure a database can provide a transactional block. -func TestDB_Update(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - if v := b.Get([]byte("foo")); v != nil { - t.Fatalf("expected nil value, got: %v", v) - } - if v := b.Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a closed database returns an error while running a transaction block -func TestDB_Update_Closed(t *testing.T) { - var db bolt.DB - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != bolt.ErrDatabaseNotOpen { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure a panic occurs while trying to commit a managed transaction. -func TestDB_Update_ManualCommit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.Update(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a panic occurs while trying to rollback a managed transaction. -func TestDB_Update_ManualRollback(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.Update(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a panic occurs while trying to commit a managed transaction. -func TestDB_View_ManualCommit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.View(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a panic occurs while trying to rollback a managed transaction. -func TestDB_View_ManualRollback(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.View(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a write transaction that panics does not hold open locks. -func TestDB_Update_Panic(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Panic during update but recover. - func() { - defer func() { - if r := recover(); r != nil { - t.Log("recover: update", r) - } - }() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - panic("omg") - }); err != nil { - t.Fatal(err) - } - }() - - // Verify we can update again. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify that our change persisted. - if err := db.Update(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a database can return an error through a read-only transactional block. -func TestDB_View_Error(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.View(func(tx *bolt.Tx) error { - return errors.New("xxx") - }); err == nil || err.Error() != "xxx" { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure a read transaction that panics does not hold open locks. -func TestDB_View_Panic(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Panic during view transaction but recover. - func() { - defer func() { - if r := recover(); r != nil { - t.Log("recover: view", r) - } - }() - - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - panic("omg") - }); err != nil { - t.Fatal(err) - } - }() - - // Verify that we can still use read transactions. - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that DB stats can be returned. -func TestDB_Stats(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - stats := db.Stats() - if stats.TxStats.PageCount != 2 { - t.Fatalf("unexpected TxStats.PageCount: %d", stats.TxStats.PageCount) - } else if stats.FreePageN != 0 { - t.Fatalf("unexpected FreePageN != 0: %d", stats.FreePageN) - } else if stats.PendingPageN != 2 { - t.Fatalf("unexpected PendingPageN != 2: %d", stats.PendingPageN) - } -} - -// Ensure that database pages are in expected order and type. -func TestDB_Consistency(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - for i := 0; i < 10; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - if err := db.Update(func(tx *bolt.Tx) error { - if p, _ := tx.Page(0); p == nil { - t.Fatal("expected page") - } else if p.Type != "meta" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(1); p == nil { - t.Fatal("expected page") - } else if p.Type != "meta" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(2); p == nil { - t.Fatal("expected page") - } else if p.Type != "free" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(3); p == nil { - t.Fatal("expected page") - } else if p.Type != "free" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(4); p == nil { - t.Fatal("expected page") - } else if p.Type != "leaf" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(5); p == nil { - t.Fatal("expected page") - } else if p.Type != "freelist" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(6); p != nil { - t.Fatal("unexpected page") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that DB stats can be subtracted from one another. -func TestDBStats_Sub(t *testing.T) { - var a, b bolt.Stats - a.TxStats.PageCount = 3 - a.FreePageN = 4 - b.TxStats.PageCount = 10 - b.FreePageN = 14 - diff := b.Sub(&a) - if diff.TxStats.PageCount != 7 { - t.Fatalf("unexpected TxStats.PageCount: %d", diff.TxStats.PageCount) - } - - // free page stats are copied from the receiver and not subtracted - if diff.FreePageN != 14 { - t.Fatalf("unexpected FreePageN: %d", diff.FreePageN) - } -} - -// Ensure two functions can perform updates in a single batch. -func TestDB_Batch(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Iterate over multiple updates in separate goroutines. - n := 2 - ch := make(chan error) - for i := 0; i < n; i++ { - go func(i int) { - ch <- db.Batch(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put(u64tob(uint64(i)), []byte{}) - }) - }(i) - } - - // Check all responses to make sure there's no error. - for i := 0; i < n; i++ { - if err := <-ch; err != nil { - t.Fatal(err) - } - } - - // Ensure data is correct. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < n; i++ { - if v := b.Get(u64tob(uint64(i))); v == nil { - t.Errorf("key not found: %d", i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestDB_Batch_Panic(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var sentinel int - var bork = &sentinel - var problem interface{} - var err error - - // Execute a function inside a batch that panics. - func() { - defer func() { - if p := recover(); p != nil { - problem = p - } - }() - err = db.Batch(func(tx *bolt.Tx) error { - panic(bork) - }) - }() - - // Verify there is no error. - if g, e := err, error(nil); g != e { - t.Fatalf("wrong error: %v != %v", g, e) - } - // Verify the panic was captured. - if g, e := problem, bork; g != e { - t.Fatalf("wrong error: %v != %v", g, e) - } -} - -func TestDB_BatchFull(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - const size = 3 - // buffered so we never leak goroutines - ch := make(chan error, size) - put := func(i int) { - ch <- db.Batch(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put(u64tob(uint64(i)), []byte{}) - }) - } - - db.MaxBatchSize = size - // high enough to never trigger here - db.MaxBatchDelay = 1 * time.Hour - - go put(1) - go put(2) - - // Give the batch a chance to exhibit bugs. - time.Sleep(10 * time.Millisecond) - - // not triggered yet - select { - case <-ch: - t.Fatalf("batch triggered too early") - default: - } - - go put(3) - - // Check all responses to make sure there's no error. - for i := 0; i < size; i++ { - if err := <-ch; err != nil { - t.Fatal(err) - } - } - - // Ensure data is correct. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 1; i <= size; i++ { - if v := b.Get(u64tob(uint64(i))); v == nil { - t.Errorf("key not found: %d", i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestDB_BatchTime(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - const size = 1 - // buffered so we never leak goroutines - ch := make(chan error, size) - put := func(i int) { - ch <- db.Batch(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put(u64tob(uint64(i)), []byte{}) - }) - } - - db.MaxBatchSize = 1000 - db.MaxBatchDelay = 0 - - go put(1) - - // Batch must trigger by time alone. - - // Check all responses to make sure there's no error. - for i := 0; i < size; i++ { - if err := <-ch; err != nil { - t.Fatal(err) - } - } - - // Ensure data is correct. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 1; i <= size; i++ { - if v := b.Get(u64tob(uint64(i))); v == nil { - t.Errorf("key not found: %d", i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func ExampleDB_Update() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Execute several commands within a read-write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Read the value back from a separate read-only transaction. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value of 'foo' is: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release the file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value of 'foo' is: bar -} - -func ExampleDB_View() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Insert data into a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("people")) - if err != nil { - return err - } - if err := b.Put([]byte("john"), []byte("doe")); err != nil { - return err - } - if err := b.Put([]byte("susy"), []byte("que")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Access data from within a read-only transactional block. - if err := db.View(func(tx *bolt.Tx) error { - v := tx.Bucket([]byte("people")).Get([]byte("john")) - fmt.Printf("John's last name is %s.\n", v) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release the file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // John's last name is doe. -} - -func ExampleDB_Begin_ReadOnly() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Create a bucket using a read-write transaction. - if err = db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - log.Fatal(err) - } - - // Create several keys in a transaction. - tx, err := db.Begin(true) - if err != nil { - log.Fatal(err) - } - b := tx.Bucket([]byte("widgets")) - if err = b.Put([]byte("john"), []byte("blue")); err != nil { - log.Fatal(err) - } - if err = b.Put([]byte("abby"), []byte("red")); err != nil { - log.Fatal(err) - } - if err = b.Put([]byte("zephyr"), []byte("purple")); err != nil { - log.Fatal(err) - } - if err = tx.Commit(); err != nil { - log.Fatal(err) - } - - // Iterate over the values in sorted key order. - tx, err = db.Begin(false) - if err != nil { - log.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - fmt.Printf("%s likes %s\n", k, v) - } - - if err = tx.Rollback(); err != nil { - log.Fatal(err) - } - - if err = db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // abby likes red - // john likes blue - // zephyr likes purple -} - -func BenchmarkDBBatchAutomatic(b *testing.B) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("bench")) - return err - }); err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - start := make(chan struct{}) - var wg sync.WaitGroup - - for round := 0; round < 1000; round++ { - wg.Add(1) - - go func(id uint32) { - defer wg.Done() - <-start - - h := fnv.New32a() - buf := make([]byte, 4) - binary.LittleEndian.PutUint32(buf, id) - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - insert := func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("bench")) - return b.Put(k, []byte("filler")) - } - if err := db.Batch(insert); err != nil { - b.Error(err) - return - } - }(uint32(round)) - } - close(start) - wg.Wait() - } - - b.StopTimer() - validateBatchBench(b, db) -} - -func BenchmarkDBBatchSingle(b *testing.B) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("bench")) - return err - }); err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - start := make(chan struct{}) - var wg sync.WaitGroup - - for round := 0; round < 1000; round++ { - wg.Add(1) - go func(id uint32) { - defer wg.Done() - <-start - - h := fnv.New32a() - buf := make([]byte, 4) - binary.LittleEndian.PutUint32(buf, id) - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - insert := func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("bench")) - return b.Put(k, []byte("filler")) - } - if err := db.Update(insert); err != nil { - b.Error(err) - return - } - }(uint32(round)) - } - close(start) - wg.Wait() - } - - b.StopTimer() - validateBatchBench(b, db) -} - -func BenchmarkDBBatchManual10x100(b *testing.B) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("bench")) - return err - }); err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - start := make(chan struct{}) - var wg sync.WaitGroup - - for major := 0; major < 10; major++ { - wg.Add(1) - go func(id uint32) { - defer wg.Done() - <-start - - insert100 := func(tx *bolt.Tx) error { - h := fnv.New32a() - buf := make([]byte, 4) - for minor := uint32(0); minor < 100; minor++ { - binary.LittleEndian.PutUint32(buf, uint32(id*100+minor)) - h.Reset() - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - b := tx.Bucket([]byte("bench")) - if err := b.Put(k, []byte("filler")); err != nil { - return err - } - } - return nil - } - if err := db.Update(insert100); err != nil { - b.Fatal(err) - } - }(uint32(major)) - } - close(start) - wg.Wait() - } - - b.StopTimer() - validateBatchBench(b, db) -} - -func validateBatchBench(b *testing.B, db *DB) { - var rollback = errors.New("sentinel error to cause rollback") - validate := func(tx *bolt.Tx) error { - bucket := tx.Bucket([]byte("bench")) - h := fnv.New32a() - buf := make([]byte, 4) - for id := uint32(0); id < 1000; id++ { - binary.LittleEndian.PutUint32(buf, id) - h.Reset() - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - v := bucket.Get(k) - if v == nil { - b.Errorf("not found id=%d key=%x", id, k) - continue - } - if g, e := v, []byte("filler"); !bytes.Equal(g, e) { - b.Errorf("bad value for id=%d key=%x: %s != %q", id, k, g, e) - } - if err := bucket.Delete(k); err != nil { - return err - } - } - // should be empty now - c := bucket.Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - b.Errorf("unexpected key: %x = %q", k, v) - } - return rollback - } - if err := db.Update(validate); err != nil && err != rollback { - b.Error(err) - } -} - -// DB is a test wrapper for bolt.DB. -type DB struct { - *bolt.DB - f string - o *bolt.Options -} - -// MustOpenDB returns a new, open DB at a temporary location. -func MustOpenDB() *DB { - return MustOpenWithOption(nil) -} - -// MustOpenDBWithOption returns a new, open DB at a temporary location with given options. -func MustOpenWithOption(o *bolt.Options) *DB { - f := tempfile() - db, err := bolt.Open(f, 0666, o) - if err != nil { - panic(err) - } - return &DB{ - DB: db, - f: f, - o: o, - } -} - -// Close closes the database and deletes the underlying file. -func (db *DB) Close() error { - // Log statistics. - if *statsFlag { - db.PrintStats() - } - - // Check database consistency after every test. - db.MustCheck() - - // Close database and remove file. - defer os.Remove(db.Path()) - return db.DB.Close() -} - -// MustClose closes the database and deletes the underlying file. Panic on error. -func (db *DB) MustClose() { - if err := db.Close(); err != nil { - panic(err) - } -} - -// MustReopen reopen the database. Panic on error. -func (db *DB) MustReopen() { - indb, err := bolt.Open(db.f, 0666, db.o) - if err != nil { - panic(err) - } - db.DB = indb -} - -// PrintStats prints the database stats -func (db *DB) PrintStats() { - var stats = db.Stats() - fmt.Printf("[db] %-20s %-20s %-20s\n", - fmt.Sprintf("pg(%d/%d)", stats.TxStats.PageCount, stats.TxStats.PageAlloc), - fmt.Sprintf("cur(%d)", stats.TxStats.CursorCount), - fmt.Sprintf("node(%d/%d)", stats.TxStats.NodeCount, stats.TxStats.NodeDeref), - ) - fmt.Printf(" %-20s %-20s %-20s\n", - fmt.Sprintf("rebal(%d/%v)", stats.TxStats.Rebalance, truncDuration(stats.TxStats.RebalanceTime)), - fmt.Sprintf("spill(%d/%v)", stats.TxStats.Spill, truncDuration(stats.TxStats.SpillTime)), - fmt.Sprintf("w(%d/%v)", stats.TxStats.Write, truncDuration(stats.TxStats.WriteTime)), - ) -} - -// MustCheck runs a consistency check on the database and panics if any errors are found. -func (db *DB) MustCheck() { - if err := db.Update(func(tx *bolt.Tx) error { - // Collect all the errors. - var errors []error - for err := range tx.Check() { - errors = append(errors, err) - if len(errors) > 10 { - break - } - } - - // If errors occurred, copy the DB and print the errors. - if len(errors) > 0 { - var path = tempfile() - if err := tx.CopyFile(path, 0600); err != nil { - panic(err) - } - - // Print errors. - fmt.Print("\n\n") - fmt.Printf("consistency check failed (%d errors)\n", len(errors)) - for _, err := range errors { - fmt.Println(err) - } - fmt.Println("") - fmt.Println("db saved to:") - fmt.Println(path) - fmt.Print("\n\n") - os.Exit(-1) - } - - return nil - }); err != nil && err != bolt.ErrDatabaseNotOpen { - panic(err) - } -} - -// CopyTempFile copies a database to a temporary file. -func (db *DB) CopyTempFile() { - path := tempfile() - if err := db.View(func(tx *bolt.Tx) error { - return tx.CopyFile(path, 0600) - }); err != nil { - panic(err) - } - fmt.Println("db copied to: ", path) -} - -// tempfile returns a temporary file path. -func tempfile() string { - f, err := ioutil.TempFile("", "bolt-") - if err != nil { - panic(err) - } - if err := f.Close(); err != nil { - panic(err) - } - if err := os.Remove(f.Name()); err != nil { - panic(err) - } - return f.Name() -} - -func trunc(b []byte, length int) []byte { - if length < len(b) { - return b[:length] - } - return b -} - -func truncDuration(d time.Duration) string { - return regexp.MustCompile(`^(\d+)(\.\d+)`).ReplaceAllString(d.String(), "$1") -} - -func fileSize(path string) int64 { - fi, err := os.Stat(path) - if err != nil { - return 0 - } - return fi.Size() -} - -// u64tob converts a uint64 into an 8-byte slice. -func u64tob(v uint64) []byte { - b := make([]byte, 8) - binary.BigEndian.PutUint64(b, v) - return b -} diff --git a/vendor/github.com/coreos/bbolt/doc.go b/vendor/github.com/coreos/bbolt/doc.go deleted file mode 100644 index cc93784..0000000 --- a/vendor/github.com/coreos/bbolt/doc.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Package bolt implements a low-level key/value store in pure Go. It supports -fully serializable transactions, ACID semantics, and lock-free MVCC with -multiple readers and a single writer. Bolt can be used for projects that -want a simple data store without the need to add large dependencies such as -Postgres or MySQL. - -Bolt is a single-level, zero-copy, B+tree data store. This means that Bolt is -optimized for fast read access and does not require recovery in the event of a -system crash. Transactions which have not finished committing will simply be -rolled back in the event of a crash. - -The design of Bolt is based on Howard Chu's LMDB database project. - -Bolt currently works on Windows, Mac OS X, and Linux. - - -Basics - -There are only a few types in Bolt: DB, Bucket, Tx, and Cursor. The DB is -a collection of buckets and is represented by a single file on disk. A bucket is -a collection of unique keys that are associated with values. - -Transactions provide either read-only or read-write access to the database. -Read-only transactions can retrieve key/value pairs and can use Cursors to -iterate over the dataset sequentially. Read-write transactions can create and -delete buckets and can insert and remove keys. Only one read-write transaction -is allowed at a time. - - -Caveats - -The database uses a read-only, memory-mapped data file to ensure that -applications cannot corrupt the database, however, this means that keys and -values returned from Bolt cannot be changed. Writing to a read-only byte slice -will cause Go to panic. - -Keys and values retrieved from the database are only valid for the life of -the transaction. When used outside the transaction, these byte slices can -point to different data or can point to invalid memory which will cause a panic. - - -*/ -package bolt diff --git a/vendor/github.com/coreos/bbolt/errors.go b/vendor/github.com/coreos/bbolt/errors.go deleted file mode 100644 index a3620a3..0000000 --- a/vendor/github.com/coreos/bbolt/errors.go +++ /dev/null @@ -1,71 +0,0 @@ -package bolt - -import "errors" - -// These errors can be returned when opening or calling methods on a DB. -var ( - // ErrDatabaseNotOpen is returned when a DB instance is accessed before it - // is opened or after it is closed. - ErrDatabaseNotOpen = errors.New("database not open") - - // ErrDatabaseOpen is returned when opening a database that is - // already open. - ErrDatabaseOpen = errors.New("database already open") - - // ErrInvalid is returned when both meta pages on a database are invalid. - // This typically occurs when a file is not a bolt database. - ErrInvalid = errors.New("invalid database") - - // ErrVersionMismatch is returned when the data file was created with a - // different version of Bolt. - ErrVersionMismatch = errors.New("version mismatch") - - // ErrChecksum is returned when either meta page checksum does not match. - ErrChecksum = errors.New("checksum error") - - // ErrTimeout is returned when a database cannot obtain an exclusive lock - // on the data file after the timeout passed to Open(). - ErrTimeout = errors.New("timeout") -) - -// These errors can occur when beginning or committing a Tx. -var ( - // ErrTxNotWritable is returned when performing a write operation on a - // read-only transaction. - ErrTxNotWritable = errors.New("tx not writable") - - // ErrTxClosed is returned when committing or rolling back a transaction - // that has already been committed or rolled back. - ErrTxClosed = errors.New("tx closed") - - // ErrDatabaseReadOnly is returned when a mutating transaction is started on a - // read-only database. - ErrDatabaseReadOnly = errors.New("database is in read-only mode") -) - -// These errors can occur when putting or deleting a value or a bucket. -var ( - // ErrBucketNotFound is returned when trying to access a bucket that has - // not been created yet. - ErrBucketNotFound = errors.New("bucket not found") - - // ErrBucketExists is returned when creating a bucket that already exists. - ErrBucketExists = errors.New("bucket already exists") - - // ErrBucketNameRequired is returned when creating a bucket with a blank name. - ErrBucketNameRequired = errors.New("bucket name required") - - // ErrKeyRequired is returned when inserting a zero-length key. - ErrKeyRequired = errors.New("key required") - - // ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize. - ErrKeyTooLarge = errors.New("key too large") - - // ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize. - ErrValueTooLarge = errors.New("value too large") - - // ErrIncompatibleValue is returned when trying create or delete a bucket - // on an existing non-bucket key or when trying to create or delete a - // non-bucket key on an existing bucket key. - ErrIncompatibleValue = errors.New("incompatible value") -) diff --git a/vendor/github.com/coreos/bbolt/freelist.go b/vendor/github.com/coreos/bbolt/freelist.go deleted file mode 100644 index 266f154..0000000 --- a/vendor/github.com/coreos/bbolt/freelist.go +++ /dev/null @@ -1,333 +0,0 @@ -package bolt - -import ( - "fmt" - "sort" - "unsafe" -) - -// txPending holds a list of pgids and corresponding allocation txns -// that are pending to be freed. -type txPending struct { - ids []pgid - alloctx []txid // txids allocating the ids - lastReleaseBegin txid // beginning txid of last matching releaseRange -} - -// freelist represents a list of all pages that are available for allocation. -// It also tracks pages that have been freed but are still in use by open transactions. -type freelist struct { - ids []pgid // all free and available free page ids. - allocs map[pgid]txid // mapping of txid that allocated a pgid. - pending map[txid]*txPending // mapping of soon-to-be free page ids by tx. - cache map[pgid]bool // fast lookup of all free and pending page ids. -} - -// newFreelist returns an empty, initialized freelist. -func newFreelist() *freelist { - return &freelist{ - allocs: make(map[pgid]txid), - pending: make(map[txid]*txPending), - cache: make(map[pgid]bool), - } -} - -// size returns the size of the page after serialization. -func (f *freelist) size() int { - n := f.count() - if n >= 0xFFFF { - // The first element will be used to store the count. See freelist.write. - n++ - } - return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * n) -} - -// count returns count of pages on the freelist -func (f *freelist) count() int { - return f.free_count() + f.pending_count() -} - -// free_count returns count of free pages -func (f *freelist) free_count() int { - return len(f.ids) -} - -// pending_count returns count of pending pages -func (f *freelist) pending_count() int { - var count int - for _, txp := range f.pending { - count += len(txp.ids) - } - return count -} - -// copyall copies into dst a list of all free ids and all pending ids in one sorted list. -// f.count returns the minimum length required for dst. -func (f *freelist) copyall(dst []pgid) { - m := make(pgids, 0, f.pending_count()) - for _, txp := range f.pending { - m = append(m, txp.ids...) - } - sort.Sort(m) - mergepgids(dst, f.ids, m) -} - -// allocate returns the starting page id of a contiguous list of pages of a given size. -// If a contiguous block cannot be found then 0 is returned. -func (f *freelist) allocate(txid txid, n int) pgid { - if len(f.ids) == 0 { - return 0 - } - - var initial, previd pgid - for i, id := range f.ids { - if id <= 1 { - panic(fmt.Sprintf("invalid page allocation: %d", id)) - } - - // Reset initial page if this is not contiguous. - if previd == 0 || id-previd != 1 { - initial = id - } - - // If we found a contiguous block then remove it and return it. - if (id-initial)+1 == pgid(n) { - // If we're allocating off the beginning then take the fast path - // and just adjust the existing slice. This will use extra memory - // temporarily but the append() in free() will realloc the slice - // as is necessary. - if (i + 1) == n { - f.ids = f.ids[i+1:] - } else { - copy(f.ids[i-n+1:], f.ids[i+1:]) - f.ids = f.ids[:len(f.ids)-n] - } - - // Remove from the free cache. - for i := pgid(0); i < pgid(n); i++ { - delete(f.cache, initial+i) - } - f.allocs[initial] = txid - return initial - } - - previd = id - } - return 0 -} - -// free releases a page and its overflow for a given transaction id. -// If the page is already free then a panic will occur. -func (f *freelist) free(txid txid, p *page) { - if p.id <= 1 { - panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id)) - } - - // Free page and all its overflow pages. - txp := f.pending[txid] - if txp == nil { - txp = &txPending{} - f.pending[txid] = txp - } - allocTxid, ok := f.allocs[p.id] - if ok { - delete(f.allocs, p.id) - } else if (p.flags & freelistPageFlag) != 0 { - // Freelist is always allocated by prior tx. - allocTxid = txid - 1 - } - - for id := p.id; id <= p.id+pgid(p.overflow); id++ { - // Verify that page is not already free. - if f.cache[id] { - panic(fmt.Sprintf("page %d already freed", id)) - } - // Add to the freelist and cache. - txp.ids = append(txp.ids, id) - txp.alloctx = append(txp.alloctx, allocTxid) - f.cache[id] = true - } -} - -// release moves all page ids for a transaction id (or older) to the freelist. -func (f *freelist) release(txid txid) { - m := make(pgids, 0) - for tid, txp := range f.pending { - if tid <= txid { - // Move transaction's pending pages to the available freelist. - // Don't remove from the cache since the page is still free. - m = append(m, txp.ids...) - delete(f.pending, tid) - } - } - sort.Sort(m) - f.ids = pgids(f.ids).merge(m) -} - -// releaseRange moves pending pages allocated within an extent [begin,end] to the free list. -func (f *freelist) releaseRange(begin, end txid) { - if begin > end { - return - } - var m pgids - for tid, txp := range f.pending { - if tid < begin || tid > end { - continue - } - // Don't recompute freed pages if ranges haven't updated. - if txp.lastReleaseBegin == begin { - continue - } - for i := 0; i < len(txp.ids); i++ { - if atx := txp.alloctx[i]; atx < begin || atx > end { - continue - } - m = append(m, txp.ids[i]) - txp.ids[i] = txp.ids[len(txp.ids)-1] - txp.ids = txp.ids[:len(txp.ids)-1] - txp.alloctx[i] = txp.alloctx[len(txp.alloctx)-1] - txp.alloctx = txp.alloctx[:len(txp.alloctx)-1] - i-- - } - txp.lastReleaseBegin = begin - if len(txp.ids) == 0 { - delete(f.pending, tid) - } - } - sort.Sort(m) - f.ids = pgids(f.ids).merge(m) -} - -// rollback removes the pages from a given pending tx. -func (f *freelist) rollback(txid txid) { - // Remove page ids from cache. - txp := f.pending[txid] - if txp == nil { - return - } - var m pgids - for i, pgid := range txp.ids { - delete(f.cache, pgid) - tx := txp.alloctx[i] - if tx == 0 { - continue - } - if tx != txid { - // Pending free aborted; restore page back to alloc list. - f.allocs[pgid] = tx - } else { - // Freed page was allocated by this txn; OK to throw away. - m = append(m, pgid) - } - } - // Remove pages from pending list and mark as free if allocated by txid. - delete(f.pending, txid) - sort.Sort(m) - f.ids = pgids(f.ids).merge(m) -} - -// freed returns whether a given page is in the free list. -func (f *freelist) freed(pgid pgid) bool { - return f.cache[pgid] -} - -// read initializes the freelist from a freelist page. -func (f *freelist) read(p *page) { - if (p.flags & freelistPageFlag) == 0 { - panic(fmt.Sprintf("invalid freelist page: %d, page type is %s", p.id, p.typ())) - } - // If the page.count is at the max uint16 value (64k) then it's considered - // an overflow and the size of the freelist is stored as the first element. - idx, count := 0, int(p.count) - if count == 0xFFFF { - idx = 1 - count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0]) - } - - // Copy the list of page ids from the freelist. - if count == 0 { - f.ids = nil - } else { - ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx : idx+count] - f.ids = make([]pgid, len(ids)) - copy(f.ids, ids) - - // Make sure they're sorted. - sort.Sort(pgids(f.ids)) - } - - // Rebuild the page cache. - f.reindex() -} - -// read initializes the freelist from a given list of ids. -func (f *freelist) readIDs(ids []pgid) { - f.ids = ids - f.reindex() -} - -// write writes the page ids onto a freelist page. All free and pending ids are -// saved to disk since in the event of a program crash, all pending ids will -// become free. -func (f *freelist) write(p *page) error { - // Combine the old free pgids and pgids waiting on an open transaction. - - // Update the header flag. - p.flags |= freelistPageFlag - - // The page.count can only hold up to 64k elements so if we overflow that - // number then we handle it by putting the size in the first element. - lenids := f.count() - if lenids == 0 { - p.count = uint16(lenids) - } else if lenids < 0xFFFF { - p.count = uint16(lenids) - f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:]) - } else { - p.count = 0xFFFF - ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(lenids) - f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:]) - } - - return nil -} - -// reload reads the freelist from a page and filters out pending items. -func (f *freelist) reload(p *page) { - f.read(p) - - // Build a cache of only pending pages. - pcache := make(map[pgid]bool) - for _, txp := range f.pending { - for _, pendingID := range txp.ids { - pcache[pendingID] = true - } - } - - // Check each page in the freelist and build a new available freelist - // with any pages not in the pending lists. - var a []pgid - for _, id := range f.ids { - if !pcache[id] { - a = append(a, id) - } - } - f.ids = a - - // Once the available list is rebuilt then rebuild the free cache so that - // it includes the available and pending free pages. - f.reindex() -} - -// reindex rebuilds the free cache based on available and pending free lists. -func (f *freelist) reindex() { - f.cache = make(map[pgid]bool, len(f.ids)) - for _, id := range f.ids { - f.cache[id] = true - } - for _, txp := range f.pending { - for _, pendingID := range txp.ids { - f.cache[pendingID] = true - } - } -} diff --git a/vendor/github.com/coreos/bbolt/freelist_test.go b/vendor/github.com/coreos/bbolt/freelist_test.go deleted file mode 100644 index 24ed4cf..0000000 --- a/vendor/github.com/coreos/bbolt/freelist_test.go +++ /dev/null @@ -1,288 +0,0 @@ -package bolt - -import ( - "math/rand" - "reflect" - "sort" - "testing" - "unsafe" -) - -// Ensure that a page is added to a transaction's freelist. -func TestFreelist_free(t *testing.T) { - f := newFreelist() - f.free(100, &page{id: 12}) - if !reflect.DeepEqual([]pgid{12}, f.pending[100].ids) { - t.Fatalf("exp=%v; got=%v", []pgid{12}, f.pending[100]) - } -} - -// Ensure that a page and its overflow is added to a transaction's freelist. -func TestFreelist_free_overflow(t *testing.T) { - f := newFreelist() - f.free(100, &page{id: 12, overflow: 3}) - if exp := []pgid{12, 13, 14, 15}; !reflect.DeepEqual(exp, f.pending[100].ids) { - t.Fatalf("exp=%v; got=%v", exp, f.pending[100]) - } -} - -// Ensure that a transaction's free pages can be released. -func TestFreelist_release(t *testing.T) { - f := newFreelist() - f.free(100, &page{id: 12, overflow: 1}) - f.free(100, &page{id: 9}) - f.free(102, &page{id: 39}) - f.release(100) - f.release(101) - if exp := []pgid{9, 12, 13}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } - - f.release(102) - if exp := []pgid{9, 12, 13, 39}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } -} - -// Ensure that releaseRange handles boundary conditions correctly -func TestFreelist_releaseRange(t *testing.T) { - type testRange struct { - begin, end txid - } - - type testPage struct { - id pgid - n int - allocTxn txid - freeTxn txid - } - - var releaseRangeTests = []struct { - title string - pagesIn []testPage - releaseRanges []testRange - wantFree []pgid - }{ - { - title: "Single pending in range", - pagesIn: []testPage{{id: 3, n: 1, allocTxn: 100, freeTxn: 200}}, - releaseRanges: []testRange{{1, 300}}, - wantFree: []pgid{3}, - }, - { - title: "Single pending with minimum end range", - pagesIn: []testPage{{id: 3, n: 1, allocTxn: 100, freeTxn: 200}}, - releaseRanges: []testRange{{1, 200}}, - wantFree: []pgid{3}, - }, - { - title: "Single pending outsize minimum end range", - pagesIn: []testPage{{id: 3, n: 1, allocTxn: 100, freeTxn: 200}}, - releaseRanges: []testRange{{1, 199}}, - wantFree: nil, - }, - { - title: "Single pending with minimum begin range", - pagesIn: []testPage{{id: 3, n: 1, allocTxn: 100, freeTxn: 200}}, - releaseRanges: []testRange{{100, 300}}, - wantFree: []pgid{3}, - }, - { - title: "Single pending outside minimum begin range", - pagesIn: []testPage{{id: 3, n: 1, allocTxn: 100, freeTxn: 200}}, - releaseRanges: []testRange{{101, 300}}, - wantFree: nil, - }, - { - title: "Single pending in minimum range", - pagesIn: []testPage{{id: 3, n: 1, allocTxn: 199, freeTxn: 200}}, - releaseRanges: []testRange{{199, 200}}, - wantFree: []pgid{3}, - }, - { - title: "Single pending and read transaction at 199", - pagesIn: []testPage{{id: 3, n: 1, allocTxn: 199, freeTxn: 200}}, - releaseRanges: []testRange{{100, 198}, {200, 300}}, - wantFree: nil, - }, - { - title: "Adjacent pending and read transactions at 199, 200", - pagesIn: []testPage{ - {id: 3, n: 1, allocTxn: 199, freeTxn: 200}, - {id: 4, n: 1, allocTxn: 200, freeTxn: 201}, - }, - releaseRanges: []testRange{ - {100, 198}, - {200, 199}, // Simulate the ranges db.freePages might produce. - {201, 300}, - }, - wantFree: nil, - }, - { - title: "Out of order ranges", - pagesIn: []testPage{ - {id: 3, n: 1, allocTxn: 199, freeTxn: 200}, - {id: 4, n: 1, allocTxn: 200, freeTxn: 201}, - }, - releaseRanges: []testRange{ - {201, 199}, - {201, 200}, - {200, 200}, - }, - wantFree: nil, - }, - { - title: "Multiple pending, read transaction at 150", - pagesIn: []testPage{ - {id: 3, n: 1, allocTxn: 100, freeTxn: 200}, - {id: 4, n: 1, allocTxn: 100, freeTxn: 125}, - {id: 5, n: 1, allocTxn: 125, freeTxn: 150}, - {id: 6, n: 1, allocTxn: 125, freeTxn: 175}, - {id: 7, n: 2, allocTxn: 150, freeTxn: 175}, - {id: 9, n: 2, allocTxn: 175, freeTxn: 200}, - }, - releaseRanges: []testRange{{50, 149}, {151, 300}}, - wantFree: []pgid{4, 9}, - }, - } - - for _, c := range releaseRangeTests { - f := newFreelist() - - for _, p := range c.pagesIn { - for i := uint64(0); i < uint64(p.n); i++ { - f.ids = append(f.ids, pgid(uint64(p.id)+i)) - } - } - for _, p := range c.pagesIn { - f.allocate(p.allocTxn, p.n) - } - - for _, p := range c.pagesIn { - f.free(p.freeTxn, &page{id: p.id}) - } - - for _, r := range c.releaseRanges { - f.releaseRange(r.begin, r.end) - } - - if exp := c.wantFree; !reflect.DeepEqual(exp, f.ids) { - t.Errorf("exp=%v; got=%v for %s", exp, f.ids, c.title) - } - } -} - -// Ensure that a freelist can find contiguous blocks of pages. -func TestFreelist_allocate(t *testing.T) { - f := newFreelist() - f.ids = []pgid{3, 4, 5, 6, 7, 9, 12, 13, 18} - if id := int(f.allocate(1, 3)); id != 3 { - t.Fatalf("exp=3; got=%v", id) - } - if id := int(f.allocate(1, 1)); id != 6 { - t.Fatalf("exp=6; got=%v", id) - } - if id := int(f.allocate(1, 3)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if id := int(f.allocate(1, 2)); id != 12 { - t.Fatalf("exp=12; got=%v", id) - } - if id := int(f.allocate(1, 1)); id != 7 { - t.Fatalf("exp=7; got=%v", id) - } - if id := int(f.allocate(1, 0)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if id := int(f.allocate(1, 0)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if exp := []pgid{9, 18}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } - - if id := int(f.allocate(1, 1)); id != 9 { - t.Fatalf("exp=9; got=%v", id) - } - if id := int(f.allocate(1, 1)); id != 18 { - t.Fatalf("exp=18; got=%v", id) - } - if id := int(f.allocate(1, 1)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if exp := []pgid{}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } -} - -// Ensure that a freelist can deserialize from a freelist page. -func TestFreelist_read(t *testing.T) { - // Create a page. - var buf [4096]byte - page := (*page)(unsafe.Pointer(&buf[0])) - page.flags = freelistPageFlag - page.count = 2 - - // Insert 2 page ids. - ids := (*[3]pgid)(unsafe.Pointer(&page.ptr)) - ids[0] = 23 - ids[1] = 50 - - // Deserialize page into a freelist. - f := newFreelist() - f.read(page) - - // Ensure that there are two page ids in the freelist. - if exp := []pgid{23, 50}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } -} - -// Ensure that a freelist can serialize into a freelist page. -func TestFreelist_write(t *testing.T) { - // Create a freelist and write it to a page. - var buf [4096]byte - f := &freelist{ids: []pgid{12, 39}, pending: make(map[txid]*txPending)} - f.pending[100] = &txPending{ids: []pgid{28, 11}} - f.pending[101] = &txPending{ids: []pgid{3}} - p := (*page)(unsafe.Pointer(&buf[0])) - if err := f.write(p); err != nil { - t.Fatal(err) - } - - // Read the page back out. - f2 := newFreelist() - f2.read(p) - - // Ensure that the freelist is correct. - // All pages should be present and in reverse order. - if exp := []pgid{3, 11, 12, 28, 39}; !reflect.DeepEqual(exp, f2.ids) { - t.Fatalf("exp=%v; got=%v", exp, f2.ids) - } -} - -func Benchmark_FreelistRelease10K(b *testing.B) { benchmark_FreelistRelease(b, 10000) } -func Benchmark_FreelistRelease100K(b *testing.B) { benchmark_FreelistRelease(b, 100000) } -func Benchmark_FreelistRelease1000K(b *testing.B) { benchmark_FreelistRelease(b, 1000000) } -func Benchmark_FreelistRelease10000K(b *testing.B) { benchmark_FreelistRelease(b, 10000000) } - -func benchmark_FreelistRelease(b *testing.B, size int) { - ids := randomPgids(size) - pending := randomPgids(len(ids) / 400) - b.ResetTimer() - for i := 0; i < b.N; i++ { - txp := &txPending{ids: pending} - f := &freelist{ids: ids, pending: map[txid]*txPending{1: txp}} - f.release(1) - } -} - -func randomPgids(n int) []pgid { - rand.Seed(42) - pgids := make(pgids, n) - for i := range pgids { - pgids[i] = pgid(rand.Int63()) - } - sort.Sort(pgids) - return pgids -} diff --git a/vendor/github.com/coreos/bbolt/node.go b/vendor/github.com/coreos/bbolt/node.go deleted file mode 100644 index f4ce240..0000000 --- a/vendor/github.com/coreos/bbolt/node.go +++ /dev/null @@ -1,604 +0,0 @@ -package bolt - -import ( - "bytes" - "fmt" - "sort" - "unsafe" -) - -// node represents an in-memory, deserialized page. -type node struct { - bucket *Bucket - isLeaf bool - unbalanced bool - spilled bool - key []byte - pgid pgid - parent *node - children nodes - inodes inodes -} - -// root returns the top-level node this node is attached to. -func (n *node) root() *node { - if n.parent == nil { - return n - } - return n.parent.root() -} - -// minKeys returns the minimum number of inodes this node should have. -func (n *node) minKeys() int { - if n.isLeaf { - return 1 - } - return 2 -} - -// size returns the size of the node after serialization. -func (n *node) size() int { - sz, elsz := pageHeaderSize, n.pageElementSize() - for i := 0; i < len(n.inodes); i++ { - item := &n.inodes[i] - sz += elsz + len(item.key) + len(item.value) - } - return sz -} - -// sizeLessThan returns true if the node is less than a given size. -// This is an optimization to avoid calculating a large node when we only need -// to know if it fits inside a certain page size. -func (n *node) sizeLessThan(v int) bool { - sz, elsz := pageHeaderSize, n.pageElementSize() - for i := 0; i < len(n.inodes); i++ { - item := &n.inodes[i] - sz += elsz + len(item.key) + len(item.value) - if sz >= v { - return false - } - } - return true -} - -// pageElementSize returns the size of each page element based on the type of node. -func (n *node) pageElementSize() int { - if n.isLeaf { - return leafPageElementSize - } - return branchPageElementSize -} - -// childAt returns the child node at a given index. -func (n *node) childAt(index int) *node { - if n.isLeaf { - panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index)) - } - return n.bucket.node(n.inodes[index].pgid, n) -} - -// childIndex returns the index of a given child node. -func (n *node) childIndex(child *node) int { - index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 }) - return index -} - -// numChildren returns the number of children. -func (n *node) numChildren() int { - return len(n.inodes) -} - -// nextSibling returns the next node with the same parent. -func (n *node) nextSibling() *node { - if n.parent == nil { - return nil - } - index := n.parent.childIndex(n) - if index >= n.parent.numChildren()-1 { - return nil - } - return n.parent.childAt(index + 1) -} - -// prevSibling returns the previous node with the same parent. -func (n *node) prevSibling() *node { - if n.parent == nil { - return nil - } - index := n.parent.childIndex(n) - if index == 0 { - return nil - } - return n.parent.childAt(index - 1) -} - -// put inserts a key/value. -func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint32) { - if pgid >= n.bucket.tx.meta.pgid { - panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", pgid, n.bucket.tx.meta.pgid)) - } else if len(oldKey) <= 0 { - panic("put: zero-length old key") - } else if len(newKey) <= 0 { - panic("put: zero-length new key") - } - - // Find insertion index. - index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, oldKey) != -1 }) - - // Add capacity and shift nodes if we don't have an exact match and need to insert. - exact := (len(n.inodes) > 0 && index < len(n.inodes) && bytes.Equal(n.inodes[index].key, oldKey)) - if !exact { - n.inodes = append(n.inodes, inode{}) - copy(n.inodes[index+1:], n.inodes[index:]) - } - - inode := &n.inodes[index] - inode.flags = flags - inode.key = newKey - inode.value = value - inode.pgid = pgid - _assert(len(inode.key) > 0, "put: zero-length inode key") -} - -// del removes a key from the node. -func (n *node) del(key []byte) { - // Find index of key. - index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) - - // Exit if the key isn't found. - if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) { - return - } - - // Delete inode from the node. - n.inodes = append(n.inodes[:index], n.inodes[index+1:]...) - - // Mark the node as needing rebalancing. - n.unbalanced = true -} - -// read initializes the node from a page. -func (n *node) read(p *page) { - n.pgid = p.id - n.isLeaf = ((p.flags & leafPageFlag) != 0) - n.inodes = make(inodes, int(p.count)) - - for i := 0; i < int(p.count); i++ { - inode := &n.inodes[i] - if n.isLeaf { - elem := p.leafPageElement(uint16(i)) - inode.flags = elem.flags - inode.key = elem.key() - inode.value = elem.value() - } else { - elem := p.branchPageElement(uint16(i)) - inode.pgid = elem.pgid - inode.key = elem.key() - } - _assert(len(inode.key) > 0, "read: zero-length inode key") - } - - // Save first key so we can find the node in the parent when we spill. - if len(n.inodes) > 0 { - n.key = n.inodes[0].key - _assert(len(n.key) > 0, "read: zero-length node key") - } else { - n.key = nil - } -} - -// write writes the items onto one or more pages. -func (n *node) write(p *page) { - // Initialize page. - if n.isLeaf { - p.flags |= leafPageFlag - } else { - p.flags |= branchPageFlag - } - - if len(n.inodes) >= 0xFFFF { - panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id)) - } - p.count = uint16(len(n.inodes)) - - // Stop here if there are no items to write. - if p.count == 0 { - return - } - - // Loop over each item and write it to the page. - b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):] - for i, item := range n.inodes { - _assert(len(item.key) > 0, "write: zero-length inode key") - - // Write the page element. - if n.isLeaf { - elem := p.leafPageElement(uint16(i)) - elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) - elem.flags = item.flags - elem.ksize = uint32(len(item.key)) - elem.vsize = uint32(len(item.value)) - } else { - elem := p.branchPageElement(uint16(i)) - elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) - elem.ksize = uint32(len(item.key)) - elem.pgid = item.pgid - _assert(elem.pgid != p.id, "write: circular dependency occurred") - } - - // If the length of key+value is larger than the max allocation size - // then we need to reallocate the byte array pointer. - // - // See: https://github.com/boltdb/bolt/pull/335 - klen, vlen := len(item.key), len(item.value) - if len(b) < klen+vlen { - b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:] - } - - // Write data for the element to the end of the page. - copy(b[0:], item.key) - b = b[klen:] - copy(b[0:], item.value) - b = b[vlen:] - } - - // DEBUG ONLY: n.dump() -} - -// split breaks up a node into multiple smaller nodes, if appropriate. -// This should only be called from the spill() function. -func (n *node) split(pageSize int) []*node { - var nodes []*node - - node := n - for { - // Split node into two. - a, b := node.splitTwo(pageSize) - nodes = append(nodes, a) - - // If we can't split then exit the loop. - if b == nil { - break - } - - // Set node to b so it gets split on the next iteration. - node = b - } - - return nodes -} - -// splitTwo breaks up a node into two smaller nodes, if appropriate. -// This should only be called from the split() function. -func (n *node) splitTwo(pageSize int) (*node, *node) { - // Ignore the split if the page doesn't have at least enough nodes for - // two pages or if the nodes can fit in a single page. - if len(n.inodes) <= (minKeysPerPage*2) || n.sizeLessThan(pageSize) { - return n, nil - } - - // Determine the threshold before starting a new node. - var fillPercent = n.bucket.FillPercent - if fillPercent < minFillPercent { - fillPercent = minFillPercent - } else if fillPercent > maxFillPercent { - fillPercent = maxFillPercent - } - threshold := int(float64(pageSize) * fillPercent) - - // Determine split position and sizes of the two pages. - splitIndex, _ := n.splitIndex(threshold) - - // Split node into two separate nodes. - // If there's no parent then we'll need to create one. - if n.parent == nil { - n.parent = &node{bucket: n.bucket, children: []*node{n}} - } - - // Create a new node and add it to the parent. - next := &node{bucket: n.bucket, isLeaf: n.isLeaf, parent: n.parent} - n.parent.children = append(n.parent.children, next) - - // Split inodes across two nodes. - next.inodes = n.inodes[splitIndex:] - n.inodes = n.inodes[:splitIndex] - - // Update the statistics. - n.bucket.tx.stats.Split++ - - return n, next -} - -// splitIndex finds the position where a page will fill a given threshold. -// It returns the index as well as the size of the first page. -// This is only be called from split(). -func (n *node) splitIndex(threshold int) (index, sz int) { - sz = pageHeaderSize - - // Loop until we only have the minimum number of keys required for the second page. - for i := 0; i < len(n.inodes)-minKeysPerPage; i++ { - index = i - inode := n.inodes[i] - elsize := n.pageElementSize() + len(inode.key) + len(inode.value) - - // If we have at least the minimum number of keys and adding another - // node would put us over the threshold then exit and return. - if i >= minKeysPerPage && sz+elsize > threshold { - break - } - - // Add the element size to the total size. - sz += elsize - } - - return -} - -// spill writes the nodes to dirty pages and splits nodes as it goes. -// Returns an error if dirty pages cannot be allocated. -func (n *node) spill() error { - var tx = n.bucket.tx - if n.spilled { - return nil - } - - // Spill child nodes first. Child nodes can materialize sibling nodes in - // the case of split-merge so we cannot use a range loop. We have to check - // the children size on every loop iteration. - sort.Sort(n.children) - for i := 0; i < len(n.children); i++ { - if err := n.children[i].spill(); err != nil { - return err - } - } - - // We no longer need the child list because it's only used for spill tracking. - n.children = nil - - // Split nodes into appropriate sizes. The first node will always be n. - var nodes = n.split(tx.db.pageSize) - for _, node := range nodes { - // Add node's page to the freelist if it's not new. - if node.pgid > 0 { - tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid)) - node.pgid = 0 - } - - // Allocate contiguous space for the node. - p, err := tx.allocate((node.size() + tx.db.pageSize - 1) / tx.db.pageSize) - if err != nil { - return err - } - - // Write the node. - if p.id >= tx.meta.pgid { - panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid)) - } - node.pgid = p.id - node.write(p) - node.spilled = true - - // Insert into parent inodes. - if node.parent != nil { - var key = node.key - if key == nil { - key = node.inodes[0].key - } - - node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0) - node.key = node.inodes[0].key - _assert(len(node.key) > 0, "spill: zero-length node key") - } - - // Update the statistics. - tx.stats.Spill++ - } - - // If the root node split and created a new root then we need to spill that - // as well. We'll clear out the children to make sure it doesn't try to respill. - if n.parent != nil && n.parent.pgid == 0 { - n.children = nil - return n.parent.spill() - } - - return nil -} - -// rebalance attempts to combine the node with sibling nodes if the node fill -// size is below a threshold or if there are not enough keys. -func (n *node) rebalance() { - if !n.unbalanced { - return - } - n.unbalanced = false - - // Update statistics. - n.bucket.tx.stats.Rebalance++ - - // Ignore if node is above threshold (25%) and has enough keys. - var threshold = n.bucket.tx.db.pageSize / 4 - if n.size() > threshold && len(n.inodes) > n.minKeys() { - return - } - - // Root node has special handling. - if n.parent == nil { - // If root node is a branch and only has one node then collapse it. - if !n.isLeaf && len(n.inodes) == 1 { - // Move root's child up. - child := n.bucket.node(n.inodes[0].pgid, n) - n.isLeaf = child.isLeaf - n.inodes = child.inodes[:] - n.children = child.children - - // Reparent all child nodes being moved. - for _, inode := range n.inodes { - if child, ok := n.bucket.nodes[inode.pgid]; ok { - child.parent = n - } - } - - // Remove old child. - child.parent = nil - delete(n.bucket.nodes, child.pgid) - child.free() - } - - return - } - - // If node has no keys then just remove it. - if n.numChildren() == 0 { - n.parent.del(n.key) - n.parent.removeChild(n) - delete(n.bucket.nodes, n.pgid) - n.free() - n.parent.rebalance() - return - } - - _assert(n.parent.numChildren() > 1, "parent must have at least 2 children") - - // Destination node is right sibling if idx == 0, otherwise left sibling. - var target *node - var useNextSibling = (n.parent.childIndex(n) == 0) - if useNextSibling { - target = n.nextSibling() - } else { - target = n.prevSibling() - } - - // If both this node and the target node are too small then merge them. - if useNextSibling { - // Reparent all child nodes being moved. - for _, inode := range target.inodes { - if child, ok := n.bucket.nodes[inode.pgid]; ok { - child.parent.removeChild(child) - child.parent = n - child.parent.children = append(child.parent.children, child) - } - } - - // Copy over inodes from target and remove target. - n.inodes = append(n.inodes, target.inodes...) - n.parent.del(target.key) - n.parent.removeChild(target) - delete(n.bucket.nodes, target.pgid) - target.free() - } else { - // Reparent all child nodes being moved. - for _, inode := range n.inodes { - if child, ok := n.bucket.nodes[inode.pgid]; ok { - child.parent.removeChild(child) - child.parent = target - child.parent.children = append(child.parent.children, child) - } - } - - // Copy over inodes to target and remove node. - target.inodes = append(target.inodes, n.inodes...) - n.parent.del(n.key) - n.parent.removeChild(n) - delete(n.bucket.nodes, n.pgid) - n.free() - } - - // Either this node or the target node was deleted from the parent so rebalance it. - n.parent.rebalance() -} - -// removes a node from the list of in-memory children. -// This does not affect the inodes. -func (n *node) removeChild(target *node) { - for i, child := range n.children { - if child == target { - n.children = append(n.children[:i], n.children[i+1:]...) - return - } - } -} - -// dereference causes the node to copy all its inode key/value references to heap memory. -// This is required when the mmap is reallocated so inodes are not pointing to stale data. -func (n *node) dereference() { - if n.key != nil { - key := make([]byte, len(n.key)) - copy(key, n.key) - n.key = key - _assert(n.pgid == 0 || len(n.key) > 0, "dereference: zero-length node key on existing node") - } - - for i := range n.inodes { - inode := &n.inodes[i] - - key := make([]byte, len(inode.key)) - copy(key, inode.key) - inode.key = key - _assert(len(inode.key) > 0, "dereference: zero-length inode key") - - value := make([]byte, len(inode.value)) - copy(value, inode.value) - inode.value = value - } - - // Recursively dereference children. - for _, child := range n.children { - child.dereference() - } - - // Update statistics. - n.bucket.tx.stats.NodeDeref++ -} - -// free adds the node's underlying page to the freelist. -func (n *node) free() { - if n.pgid != 0 { - n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid)) - n.pgid = 0 - } -} - -// dump writes the contents of the node to STDERR for debugging purposes. -/* -func (n *node) dump() { - // Write node header. - var typ = "branch" - if n.isLeaf { - typ = "leaf" - } - warnf("[NODE %d {type=%s count=%d}]", n.pgid, typ, len(n.inodes)) - - // Write out abbreviated version of each item. - for _, item := range n.inodes { - if n.isLeaf { - if item.flags&bucketLeafFlag != 0 { - bucket := (*bucket)(unsafe.Pointer(&item.value[0])) - warnf("+L %08x -> (bucket root=%d)", trunc(item.key, 4), bucket.root) - } else { - warnf("+L %08x -> %08x", trunc(item.key, 4), trunc(item.value, 4)) - } - } else { - warnf("+B %08x -> pgid=%d", trunc(item.key, 4), item.pgid) - } - } - warn("") -} -*/ - -type nodes []*node - -func (s nodes) Len() int { return len(s) } -func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[0].key, s[j].inodes[0].key) == -1 } - -// inode represents an internal node inside of a node. -// It can be used to point to elements in a page or point -// to an element which hasn't been added to a page yet. -type inode struct { - flags uint32 - pgid pgid - key []byte - value []byte -} - -type inodes []inode diff --git a/vendor/github.com/coreos/bbolt/node_test.go b/vendor/github.com/coreos/bbolt/node_test.go deleted file mode 100644 index fa5d10f..0000000 --- a/vendor/github.com/coreos/bbolt/node_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package bolt - -import ( - "testing" - "unsafe" -) - -// Ensure that a node can insert a key/value. -func TestNode_put(t *testing.T) { - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{meta: &meta{pgid: 1}}}} - n.put([]byte("baz"), []byte("baz"), []byte("2"), 0, 0) - n.put([]byte("foo"), []byte("foo"), []byte("0"), 0, 0) - n.put([]byte("bar"), []byte("bar"), []byte("1"), 0, 0) - n.put([]byte("foo"), []byte("foo"), []byte("3"), 0, leafPageFlag) - - if len(n.inodes) != 3 { - t.Fatalf("exp=3; got=%d", len(n.inodes)) - } - if k, v := n.inodes[0].key, n.inodes[0].value; string(k) != "bar" || string(v) != "1" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n.inodes[1].key, n.inodes[1].value; string(k) != "baz" || string(v) != "2" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n.inodes[2].key, n.inodes[2].value; string(k) != "foo" || string(v) != "3" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if n.inodes[2].flags != uint32(leafPageFlag) { - t.Fatalf("not a leaf: %d", n.inodes[2].flags) - } -} - -// Ensure that a node can deserialize from a leaf page. -func TestNode_read_LeafPage(t *testing.T) { - // Create a page. - var buf [4096]byte - page := (*page)(unsafe.Pointer(&buf[0])) - page.flags = leafPageFlag - page.count = 2 - - // Insert 2 elements at the beginning. sizeof(leafPageElement) == 16 - nodes := (*[3]leafPageElement)(unsafe.Pointer(&page.ptr)) - nodes[0] = leafPageElement{flags: 0, pos: 32, ksize: 3, vsize: 4} // pos = sizeof(leafPageElement) * 2 - nodes[1] = leafPageElement{flags: 0, pos: 23, ksize: 10, vsize: 3} // pos = sizeof(leafPageElement) + 3 + 4 - - // Write data for the nodes at the end. - data := (*[4096]byte)(unsafe.Pointer(&nodes[2])) - copy(data[:], []byte("barfooz")) - copy(data[7:], []byte("helloworldbye")) - - // Deserialize page into a leaf. - n := &node{} - n.read(page) - - // Check that there are two inodes with correct data. - if !n.isLeaf { - t.Fatal("expected leaf") - } - if len(n.inodes) != 2 { - t.Fatalf("exp=2; got=%d", len(n.inodes)) - } - if k, v := n.inodes[0].key, n.inodes[0].value; string(k) != "bar" || string(v) != "fooz" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n.inodes[1].key, n.inodes[1].value; string(k) != "helloworld" || string(v) != "bye" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } -} - -// Ensure that a node can serialize into a leaf page. -func TestNode_write_LeafPage(t *testing.T) { - // Create a node. - n := &node{isLeaf: true, inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("susy"), []byte("susy"), []byte("que"), 0, 0) - n.put([]byte("ricki"), []byte("ricki"), []byte("lake"), 0, 0) - n.put([]byte("john"), []byte("john"), []byte("johnson"), 0, 0) - - // Write it to a page. - var buf [4096]byte - p := (*page)(unsafe.Pointer(&buf[0])) - n.write(p) - - // Read the page back in. - n2 := &node{} - n2.read(p) - - // Check that the two pages are the same. - if len(n2.inodes) != 3 { - t.Fatalf("exp=3; got=%d", len(n2.inodes)) - } - if k, v := n2.inodes[0].key, n2.inodes[0].value; string(k) != "john" || string(v) != "johnson" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n2.inodes[1].key, n2.inodes[1].value; string(k) != "ricki" || string(v) != "lake" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n2.inodes[2].key, n2.inodes[2].value; string(k) != "susy" || string(v) != "que" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } -} - -// Ensure that a node can split into appropriate subgroups. -func TestNode_split(t *testing.T) { - // Create a node. - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("00000001"), []byte("00000001"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000002"), []byte("00000002"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000003"), []byte("00000003"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000004"), []byte("00000004"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000005"), []byte("00000005"), []byte("0123456701234567"), 0, 0) - - // Split between 2 & 3. - n.split(100) - - var parent = n.parent - if len(parent.children) != 2 { - t.Fatalf("exp=2; got=%d", len(parent.children)) - } - if len(parent.children[0].inodes) != 2 { - t.Fatalf("exp=2; got=%d", len(parent.children[0].inodes)) - } - if len(parent.children[1].inodes) != 3 { - t.Fatalf("exp=3; got=%d", len(parent.children[1].inodes)) - } -} - -// Ensure that a page with the minimum number of inodes just returns a single node. -func TestNode_split_MinKeys(t *testing.T) { - // Create a node. - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("00000001"), []byte("00000001"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000002"), []byte("00000002"), []byte("0123456701234567"), 0, 0) - - // Split. - n.split(20) - if n.parent != nil { - t.Fatalf("expected nil parent") - } -} - -// Ensure that a node that has keys that all fit on a page just returns one leaf. -func TestNode_split_SinglePage(t *testing.T) { - // Create a node. - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("00000001"), []byte("00000001"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000002"), []byte("00000002"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000003"), []byte("00000003"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000004"), []byte("00000004"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000005"), []byte("00000005"), []byte("0123456701234567"), 0, 0) - - // Split. - n.split(4096) - if n.parent != nil { - t.Fatalf("expected nil parent") - } -} diff --git a/vendor/github.com/coreos/bbolt/page.go b/vendor/github.com/coreos/bbolt/page.go deleted file mode 100644 index cde403a..0000000 --- a/vendor/github.com/coreos/bbolt/page.go +++ /dev/null @@ -1,197 +0,0 @@ -package bolt - -import ( - "fmt" - "os" - "sort" - "unsafe" -) - -const pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr)) - -const minKeysPerPage = 2 - -const branchPageElementSize = int(unsafe.Sizeof(branchPageElement{})) -const leafPageElementSize = int(unsafe.Sizeof(leafPageElement{})) - -const ( - branchPageFlag = 0x01 - leafPageFlag = 0x02 - metaPageFlag = 0x04 - freelistPageFlag = 0x10 -) - -const ( - bucketLeafFlag = 0x01 -) - -type pgid uint64 - -type page struct { - id pgid - flags uint16 - count uint16 - overflow uint32 - ptr uintptr -} - -// typ returns a human readable page type string used for debugging. -func (p *page) typ() string { - if (p.flags & branchPageFlag) != 0 { - return "branch" - } else if (p.flags & leafPageFlag) != 0 { - return "leaf" - } else if (p.flags & metaPageFlag) != 0 { - return "meta" - } else if (p.flags & freelistPageFlag) != 0 { - return "freelist" - } - return fmt.Sprintf("unknown<%02x>", p.flags) -} - -// meta returns a pointer to the metadata section of the page. -func (p *page) meta() *meta { - return (*meta)(unsafe.Pointer(&p.ptr)) -} - -// leafPageElement retrieves the leaf node by index -func (p *page) leafPageElement(index uint16) *leafPageElement { - n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index] - return n -} - -// leafPageElements retrieves a list of leaf nodes. -func (p *page) leafPageElements() []leafPageElement { - if p.count == 0 { - return nil - } - return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:] -} - -// branchPageElement retrieves the branch node by index -func (p *page) branchPageElement(index uint16) *branchPageElement { - return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index] -} - -// branchPageElements retrieves a list of branch nodes. -func (p *page) branchPageElements() []branchPageElement { - if p.count == 0 { - return nil - } - return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:] -} - -// dump writes n bytes of the page to STDERR as hex output. -func (p *page) hexdump(n int) { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n] - fmt.Fprintf(os.Stderr, "%x\n", buf) -} - -type pages []*page - -func (s pages) Len() int { return len(s) } -func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s pages) Less(i, j int) bool { return s[i].id < s[j].id } - -// branchPageElement represents a node on a branch page. -type branchPageElement struct { - pos uint32 - ksize uint32 - pgid pgid -} - -// key returns a byte slice of the node key. -func (n *branchPageElement) key() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize] -} - -// leafPageElement represents a node on a leaf page. -type leafPageElement struct { - flags uint32 - pos uint32 - ksize uint32 - vsize uint32 -} - -// key returns a byte slice of the node key. -func (n *leafPageElement) key() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize:n.ksize] -} - -// value returns a byte slice of the node value. -func (n *leafPageElement) value() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize] -} - -// PageInfo represents human readable information about a page. -type PageInfo struct { - ID int - Type string - Count int - OverflowCount int -} - -type pgids []pgid - -func (s pgids) Len() int { return len(s) } -func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s pgids) Less(i, j int) bool { return s[i] < s[j] } - -// merge returns the sorted union of a and b. -func (a pgids) merge(b pgids) pgids { - // Return the opposite slice if one is nil. - if len(a) == 0 { - return b - } - if len(b) == 0 { - return a - } - merged := make(pgids, len(a)+len(b)) - mergepgids(merged, a, b) - return merged -} - -// mergepgids copies the sorted union of a and b into dst. -// If dst is too small, it panics. -func mergepgids(dst, a, b pgids) { - if len(dst) < len(a)+len(b) { - panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(dst), len(a), len(b))) - } - // Copy in the opposite slice if one is nil. - if len(a) == 0 { - copy(dst, b) - return - } - if len(b) == 0 { - copy(dst, a) - return - } - - // Merged will hold all elements from both lists. - merged := dst[:0] - - // Assign lead to the slice with a lower starting value, follow to the higher value. - lead, follow := a, b - if b[0] < a[0] { - lead, follow = b, a - } - - // Continue while there are elements in the lead. - for len(lead) > 0 { - // Merge largest prefix of lead that is ahead of follow[0]. - n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] }) - merged = append(merged, lead[:n]...) - if n >= len(lead) { - break - } - - // Swap lead and follow. - lead, follow = follow, lead[n:] - } - - // Append what's left in follow. - _ = append(merged, follow...) -} diff --git a/vendor/github.com/coreos/bbolt/page_test.go b/vendor/github.com/coreos/bbolt/page_test.go deleted file mode 100644 index 59f4a30..0000000 --- a/vendor/github.com/coreos/bbolt/page_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package bolt - -import ( - "reflect" - "sort" - "testing" - "testing/quick" -) - -// Ensure that the page type can be returned in human readable format. -func TestPage_typ(t *testing.T) { - if typ := (&page{flags: branchPageFlag}).typ(); typ != "branch" { - t.Fatalf("exp=branch; got=%v", typ) - } - if typ := (&page{flags: leafPageFlag}).typ(); typ != "leaf" { - t.Fatalf("exp=leaf; got=%v", typ) - } - if typ := (&page{flags: metaPageFlag}).typ(); typ != "meta" { - t.Fatalf("exp=meta; got=%v", typ) - } - if typ := (&page{flags: freelistPageFlag}).typ(); typ != "freelist" { - t.Fatalf("exp=freelist; got=%v", typ) - } - if typ := (&page{flags: 20000}).typ(); typ != "unknown<4e20>" { - t.Fatalf("exp=unknown<4e20>; got=%v", typ) - } -} - -// Ensure that the hexdump debugging function doesn't blow up. -func TestPage_dump(t *testing.T) { - (&page{id: 256}).hexdump(16) -} - -func TestPgids_merge(t *testing.T) { - a := pgids{4, 5, 6, 10, 11, 12, 13, 27} - b := pgids{1, 3, 8, 9, 25, 30} - c := a.merge(b) - if !reflect.DeepEqual(c, pgids{1, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 25, 27, 30}) { - t.Errorf("mismatch: %v", c) - } - - a = pgids{4, 5, 6, 10, 11, 12, 13, 27, 35, 36} - b = pgids{8, 9, 25, 30} - c = a.merge(b) - if !reflect.DeepEqual(c, pgids{4, 5, 6, 8, 9, 10, 11, 12, 13, 25, 27, 30, 35, 36}) { - t.Errorf("mismatch: %v", c) - } -} - -func TestPgids_merge_quick(t *testing.T) { - if err := quick.Check(func(a, b pgids) bool { - // Sort incoming lists. - sort.Sort(a) - sort.Sort(b) - - // Merge the two lists together. - got := a.merge(b) - - // The expected value should be the two lists combined and sorted. - exp := append(a, b...) - sort.Sort(exp) - - if !reflect.DeepEqual(exp, got) { - t.Errorf("\nexp=%+v\ngot=%+v\n", exp, got) - return false - } - - return true - }, nil); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/coreos/bbolt/quick_test.go b/vendor/github.com/coreos/bbolt/quick_test.go deleted file mode 100644 index 9e27792..0000000 --- a/vendor/github.com/coreos/bbolt/quick_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package bolt_test - -import ( - "bytes" - "flag" - "fmt" - "math/rand" - "os" - "reflect" - "testing/quick" - "time" -) - -// testing/quick defaults to 5 iterations and a random seed. -// You can override these settings from the command line: -// -// -quick.count The number of iterations to perform. -// -quick.seed The seed to use for randomizing. -// -quick.maxitems The maximum number of items to insert into a DB. -// -quick.maxksize The maximum size of a key. -// -quick.maxvsize The maximum size of a value. -// - -var qcount, qseed, qmaxitems, qmaxksize, qmaxvsize int - -func init() { - flag.IntVar(&qcount, "quick.count", 5, "") - flag.IntVar(&qseed, "quick.seed", int(time.Now().UnixNano())%100000, "") - flag.IntVar(&qmaxitems, "quick.maxitems", 1000, "") - flag.IntVar(&qmaxksize, "quick.maxksize", 1024, "") - flag.IntVar(&qmaxvsize, "quick.maxvsize", 1024, "") - flag.Parse() - fmt.Fprintln(os.Stderr, "seed:", qseed) - fmt.Fprintf(os.Stderr, "quick settings: count=%v, items=%v, ksize=%v, vsize=%v\n", qcount, qmaxitems, qmaxksize, qmaxvsize) -} - -func qconfig() *quick.Config { - return &quick.Config{ - MaxCount: qcount, - Rand: rand.New(rand.NewSource(int64(qseed))), - } -} - -type testdata []testdataitem - -func (t testdata) Len() int { return len(t) } -func (t testdata) Swap(i, j int) { t[i], t[j] = t[j], t[i] } -func (t testdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == -1 } - -func (t testdata) Generate(rand *rand.Rand, size int) reflect.Value { - n := rand.Intn(qmaxitems-1) + 1 - items := make(testdata, n) - used := make(map[string]bool) - for i := 0; i < n; i++ { - item := &items[i] - // Ensure that keys are unique by looping until we find one that we have not already used. - for { - item.Key = randByteSlice(rand, 1, qmaxksize) - if !used[string(item.Key)] { - used[string(item.Key)] = true - break - } - } - item.Value = randByteSlice(rand, 0, qmaxvsize) - } - return reflect.ValueOf(items) -} - -type revtestdata []testdataitem - -func (t revtestdata) Len() int { return len(t) } -func (t revtestdata) Swap(i, j int) { t[i], t[j] = t[j], t[i] } -func (t revtestdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == 1 } - -type testdataitem struct { - Key []byte - Value []byte -} - -func randByteSlice(rand *rand.Rand, minSize, maxSize int) []byte { - n := rand.Intn(maxSize-minSize) + minSize - b := make([]byte, n) - for i := 0; i < n; i++ { - b[i] = byte(rand.Intn(255)) - } - return b -} diff --git a/vendor/github.com/coreos/bbolt/simulation_no_freelist_sync_test.go b/vendor/github.com/coreos/bbolt/simulation_no_freelist_sync_test.go deleted file mode 100644 index da2031e..0000000 --- a/vendor/github.com/coreos/bbolt/simulation_no_freelist_sync_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package bolt_test - -import ( - "testing" - - "github.com/coreos/bbolt" -) - -func TestSimulateNoFreeListSync_1op_1p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 1, 1) -} -func TestSimulateNoFreeListSync_10op_1p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 10, 1) -} -func TestSimulateNoFreeListSync_100op_1p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 100, 1) -} -func TestSimulateNoFreeListSync_1000op_1p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 1000, 1) -} -func TestSimulateNoFreeListSync_10000op_1p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 10000, 1) -} -func TestSimulateNoFreeListSync_10op_10p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 10, 10) -} -func TestSimulateNoFreeListSync_100op_10p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 100, 10) -} -func TestSimulateNoFreeListSync_1000op_10p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 1000, 10) -} -func TestSimulateNoFreeListSync_10000op_10p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 10000, 10) -} -func TestSimulateNoFreeListSync_100op_100p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 100, 100) -} -func TestSimulateNoFreeListSync_1000op_100p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 1000, 100) -} -func TestSimulateNoFreeListSync_10000op_100p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 10000, 100) -} -func TestSimulateNoFreeListSync_10000op_1000p(t *testing.T) { - testSimulate(t, &bolt.Options{NoFreelistSync: true}, 8, 10000, 1000) -} diff --git a/vendor/github.com/coreos/bbolt/simulation_test.go b/vendor/github.com/coreos/bbolt/simulation_test.go deleted file mode 100644 index a5889c0..0000000 --- a/vendor/github.com/coreos/bbolt/simulation_test.go +++ /dev/null @@ -1,336 +0,0 @@ -package bolt_test - -import ( - "bytes" - "fmt" - "math/rand" - "sync" - "testing" - - "github.com/coreos/bbolt" -) - -func TestSimulate_1op_1p(t *testing.T) { testSimulate(t, nil, 1, 1, 1) } -func TestSimulate_10op_1p(t *testing.T) { testSimulate(t, nil, 1, 10, 1) } -func TestSimulate_100op_1p(t *testing.T) { testSimulate(t, nil, 1, 100, 1) } -func TestSimulate_1000op_1p(t *testing.T) { testSimulate(t, nil, 1, 1000, 1) } -func TestSimulate_10000op_1p(t *testing.T) { testSimulate(t, nil, 1, 10000, 1) } - -func TestSimulate_10op_10p(t *testing.T) { testSimulate(t, nil, 1, 10, 10) } -func TestSimulate_100op_10p(t *testing.T) { testSimulate(t, nil, 1, 100, 10) } -func TestSimulate_1000op_10p(t *testing.T) { testSimulate(t, nil, 1, 1000, 10) } -func TestSimulate_10000op_10p(t *testing.T) { testSimulate(t, nil, 1, 10000, 10) } - -func TestSimulate_100op_100p(t *testing.T) { testSimulate(t, nil, 1, 100, 100) } -func TestSimulate_1000op_100p(t *testing.T) { testSimulate(t, nil, 1, 1000, 100) } -func TestSimulate_10000op_100p(t *testing.T) { testSimulate(t, nil, 1, 10000, 100) } - -func TestSimulate_10000op_1000p(t *testing.T) { testSimulate(t, nil, 1, 10000, 1000) } - -// Randomly generate operations on a given database with multiple clients to ensure consistency and thread safety. -func testSimulate(t *testing.T, openOption *bolt.Options, round, threadCount, parallelism int) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - rand.Seed(int64(qseed)) - - // A list of operations that readers and writers can perform. - var readerHandlers = []simulateHandler{simulateGetHandler} - var writerHandlers = []simulateHandler{simulateGetHandler, simulatePutHandler} - - var versions = make(map[int]*QuickDB) - versions[1] = NewQuickDB() - - db := MustOpenWithOption(openOption) - defer db.MustClose() - - var mutex sync.Mutex - - // Run n threads in parallel, each with their own operation. - var wg sync.WaitGroup - - for n := 0; n < round; n++ { - - var threads = make(chan bool, parallelism) - var i int - for { - threads <- true - wg.Add(1) - writable := ((rand.Int() % 100) < 20) // 20% writers - - // Choose an operation to execute. - var handler simulateHandler - if writable { - handler = writerHandlers[rand.Intn(len(writerHandlers))] - } else { - handler = readerHandlers[rand.Intn(len(readerHandlers))] - } - - // Execute a thread for the given operation. - go func(writable bool, handler simulateHandler) { - defer wg.Done() - - // Start transaction. - tx, err := db.Begin(writable) - if err != nil { - t.Fatal("tx begin: ", err) - } - - // Obtain current state of the dataset. - mutex.Lock() - var qdb = versions[tx.ID()] - if writable { - qdb = versions[tx.ID()-1].Copy() - } - mutex.Unlock() - - // Make sure we commit/rollback the tx at the end and update the state. - if writable { - defer func() { - mutex.Lock() - versions[tx.ID()] = qdb - mutex.Unlock() - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - }() - } else { - defer func() { _ = tx.Rollback() }() - } - - // Ignore operation if we don't have data yet. - if qdb == nil { - return - } - - // Execute handler. - handler(tx, qdb) - - // Release a thread back to the scheduling loop. - <-threads - }(writable, handler) - - i++ - if i > threadCount { - break - } - } - - // Wait until all threads are done. - wg.Wait() - - db.MustClose() - db.MustReopen() - } -} - -type simulateHandler func(tx *bolt.Tx, qdb *QuickDB) - -// Retrieves a key from the database and verifies that it is what is expected. -func simulateGetHandler(tx *bolt.Tx, qdb *QuickDB) { - // Randomly retrieve an existing exist. - keys := qdb.Rand() - if len(keys) == 0 { - return - } - - // Retrieve root bucket. - b := tx.Bucket(keys[0]) - if b == nil { - panic(fmt.Sprintf("bucket[0] expected: %08x\n", trunc(keys[0], 4))) - } - - // Drill into nested buckets. - for _, key := range keys[1 : len(keys)-1] { - b = b.Bucket(key) - if b == nil { - panic(fmt.Sprintf("bucket[n] expected: %v -> %v\n", keys, key)) - } - } - - // Verify key/value on the final bucket. - expected := qdb.Get(keys) - actual := b.Get(keys[len(keys)-1]) - if !bytes.Equal(actual, expected) { - fmt.Println("=== EXPECTED ===") - fmt.Println(expected) - fmt.Println("=== ACTUAL ===") - fmt.Println(actual) - fmt.Println("=== END ===") - panic("value mismatch") - } -} - -// Inserts a key into the database. -func simulatePutHandler(tx *bolt.Tx, qdb *QuickDB) { - var err error - keys, value := randKeys(), randValue() - - // Retrieve root bucket. - b := tx.Bucket(keys[0]) - if b == nil { - b, err = tx.CreateBucket(keys[0]) - if err != nil { - panic("create bucket: " + err.Error()) - } - } - - // Create nested buckets, if necessary. - for _, key := range keys[1 : len(keys)-1] { - child := b.Bucket(key) - if child != nil { - b = child - } else { - b, err = b.CreateBucket(key) - if err != nil { - panic("create bucket: " + err.Error()) - } - } - } - - // Insert into database. - if err := b.Put(keys[len(keys)-1], value); err != nil { - panic("put: " + err.Error()) - } - - // Insert into in-memory database. - qdb.Put(keys, value) -} - -// QuickDB is an in-memory database that replicates the functionality of the -// Bolt DB type except that it is entirely in-memory. It is meant for testing -// that the Bolt database is consistent. -type QuickDB struct { - sync.RWMutex - m map[string]interface{} -} - -// NewQuickDB returns an instance of QuickDB. -func NewQuickDB() *QuickDB { - return &QuickDB{m: make(map[string]interface{})} -} - -// Get retrieves the value at a key path. -func (db *QuickDB) Get(keys [][]byte) []byte { - db.RLock() - defer db.RUnlock() - - m := db.m - for _, key := range keys[:len(keys)-1] { - value := m[string(key)] - if value == nil { - return nil - } - switch value := value.(type) { - case map[string]interface{}: - m = value - case []byte: - return nil - } - } - - // Only return if it's a simple value. - if value, ok := m[string(keys[len(keys)-1])].([]byte); ok { - return value - } - return nil -} - -// Put inserts a value into a key path. -func (db *QuickDB) Put(keys [][]byte, value []byte) { - db.Lock() - defer db.Unlock() - - // Build buckets all the way down the key path. - m := db.m - for _, key := range keys[:len(keys)-1] { - if _, ok := m[string(key)].([]byte); ok { - return // Keypath intersects with a simple value. Do nothing. - } - - if m[string(key)] == nil { - m[string(key)] = make(map[string]interface{}) - } - m = m[string(key)].(map[string]interface{}) - } - - // Insert value into the last key. - m[string(keys[len(keys)-1])] = value -} - -// Rand returns a random key path that points to a simple value. -func (db *QuickDB) Rand() [][]byte { - db.RLock() - defer db.RUnlock() - if len(db.m) == 0 { - return nil - } - var keys [][]byte - db.rand(db.m, &keys) - return keys -} - -func (db *QuickDB) rand(m map[string]interface{}, keys *[][]byte) { - i, index := 0, rand.Intn(len(m)) - for k, v := range m { - if i == index { - *keys = append(*keys, []byte(k)) - if v, ok := v.(map[string]interface{}); ok { - db.rand(v, keys) - } - return - } - i++ - } - panic("quickdb rand: out-of-range") -} - -// Copy copies the entire database. -func (db *QuickDB) Copy() *QuickDB { - db.RLock() - defer db.RUnlock() - return &QuickDB{m: db.copy(db.m)} -} - -func (db *QuickDB) copy(m map[string]interface{}) map[string]interface{} { - clone := make(map[string]interface{}, len(m)) - for k, v := range m { - switch v := v.(type) { - case map[string]interface{}: - clone[k] = db.copy(v) - default: - clone[k] = v - } - } - return clone -} - -func randKey() []byte { - var min, max = 1, 1024 - n := rand.Intn(max-min) + min - b := make([]byte, n) - for i := 0; i < n; i++ { - b[i] = byte(rand.Intn(255)) - } - return b -} - -func randKeys() [][]byte { - var keys [][]byte - var count = rand.Intn(2) + 2 - for i := 0; i < count; i++ { - keys = append(keys, randKey()) - } - return keys -} - -func randValue() []byte { - n := rand.Intn(8192) - b := make([]byte, n) - for i := 0; i < n; i++ { - b[i] = byte(rand.Intn(255)) - } - return b -} diff --git a/vendor/github.com/coreos/bbolt/tx.go b/vendor/github.com/coreos/bbolt/tx.go deleted file mode 100644 index 41a9bc6..0000000 --- a/vendor/github.com/coreos/bbolt/tx.go +++ /dev/null @@ -1,707 +0,0 @@ -package bolt - -import ( - "fmt" - "io" - "os" - "sort" - "strings" - "time" - "unsafe" -) - -// txid represents the internal transaction identifier. -type txid uint64 - -// Tx represents a read-only or read/write transaction on the database. -// Read-only transactions can be used for retrieving values for keys and creating cursors. -// Read/write transactions can create and remove buckets and create and remove keys. -// -// IMPORTANT: You must commit or rollback transactions when you are done with -// them. Pages can not be reclaimed by the writer until no more transactions -// are using them. A long running read transaction can cause the database to -// quickly grow. -type Tx struct { - writable bool - managed bool - db *DB - meta *meta - root Bucket - pages map[pgid]*page - stats TxStats - commitHandlers []func() - - // WriteFlag specifies the flag for write-related methods like WriteTo(). - // Tx opens the database file with the specified flag to copy the data. - // - // By default, the flag is unset, which works well for mostly in-memory - // workloads. For databases that are much larger than available RAM, - // set the flag to syscall.O_DIRECT to avoid trashing the page cache. - WriteFlag int -} - -// init initializes the transaction. -func (tx *Tx) init(db *DB) { - tx.db = db - tx.pages = nil - - // Copy the meta page since it can be changed by the writer. - tx.meta = &meta{} - db.meta().copy(tx.meta) - - // Copy over the root bucket. - tx.root = newBucket(tx) - tx.root.bucket = &bucket{} - *tx.root.bucket = tx.meta.root - - // Increment the transaction id and add a page cache for writable transactions. - if tx.writable { - tx.pages = make(map[pgid]*page) - tx.meta.txid += txid(1) - } -} - -// ID returns the transaction id. -func (tx *Tx) ID() int { - return int(tx.meta.txid) -} - -// DB returns a reference to the database that created the transaction. -func (tx *Tx) DB() *DB { - return tx.db -} - -// Size returns current database size in bytes as seen by this transaction. -func (tx *Tx) Size() int64 { - return int64(tx.meta.pgid) * int64(tx.db.pageSize) -} - -// Writable returns whether the transaction can perform write operations. -func (tx *Tx) Writable() bool { - return tx.writable -} - -// Cursor creates a cursor associated with the root bucket. -// All items in the cursor will return a nil value because all root bucket keys point to buckets. -// The cursor is only valid as long as the transaction is open. -// Do not use a cursor after the transaction is closed. -func (tx *Tx) Cursor() *Cursor { - return tx.root.Cursor() -} - -// Stats retrieves a copy of the current transaction statistics. -func (tx *Tx) Stats() TxStats { - return tx.stats -} - -// Bucket retrieves a bucket by name. -// Returns nil if the bucket does not exist. -// The bucket instance is only valid for the lifetime of the transaction. -func (tx *Tx) Bucket(name []byte) *Bucket { - return tx.root.Bucket(name) -} - -// CreateBucket creates a new bucket. -// Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) { - return tx.root.CreateBucket(name) -} - -// CreateBucketIfNotExists creates a new bucket if it doesn't already exist. -// Returns an error if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) { - return tx.root.CreateBucketIfNotExists(name) -} - -// DeleteBucket deletes a bucket. -// Returns an error if the bucket cannot be found or if the key represents a non-bucket value. -func (tx *Tx) DeleteBucket(name []byte) error { - return tx.root.DeleteBucket(name) -} - -// ForEach executes a function for each bucket in the root. -// If the provided function returns an error then the iteration is stopped and -// the error is returned to the caller. -func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error { - return tx.root.ForEach(func(k, v []byte) error { - return fn(k, tx.root.Bucket(k)) - }) -} - -// OnCommit adds a handler function to be executed after the transaction successfully commits. -func (tx *Tx) OnCommit(fn func()) { - tx.commitHandlers = append(tx.commitHandlers, fn) -} - -// Commit writes all changes to disk and updates the meta page. -// Returns an error if a disk write error occurs, or if Commit is -// called on a read-only transaction. -func (tx *Tx) Commit() error { - _assert(!tx.managed, "managed tx commit not allowed") - if tx.db == nil { - return ErrTxClosed - } else if !tx.writable { - return ErrTxNotWritable - } - - // TODO(benbjohnson): Use vectorized I/O to write out dirty pages. - - // Rebalance nodes which have had deletions. - var startTime = time.Now() - tx.root.rebalance() - if tx.stats.Rebalance > 0 { - tx.stats.RebalanceTime += time.Since(startTime) - } - - // spill data onto dirty pages. - startTime = time.Now() - if err := tx.root.spill(); err != nil { - tx.rollback() - return err - } - tx.stats.SpillTime += time.Since(startTime) - - // Free the old root bucket. - tx.meta.root.root = tx.root.root - - // Free the old freelist because commit writes out a fresh freelist. - if tx.meta.freelist != pgidNoFreelist { - tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist)) - } - - if !tx.db.NoFreelistSync { - err := tx.commitFreelist() - if err != nil { - return err - } - } else { - tx.meta.freelist = pgidNoFreelist - } - - // Write dirty pages to disk. - startTime = time.Now() - if err := tx.write(); err != nil { - tx.rollback() - return err - } - - // If strict mode is enabled then perform a consistency check. - // Only the first consistency error is reported in the panic. - if tx.db.StrictMode { - ch := tx.Check() - var errs []string - for { - err, ok := <-ch - if !ok { - break - } - errs = append(errs, err.Error()) - } - if len(errs) > 0 { - panic("check fail: " + strings.Join(errs, "\n")) - } - } - - // Write meta to disk. - if err := tx.writeMeta(); err != nil { - tx.rollback() - return err - } - tx.stats.WriteTime += time.Since(startTime) - - // Finalize the transaction. - tx.close() - - // Execute commit handlers now that the locks have been removed. - for _, fn := range tx.commitHandlers { - fn() - } - - return nil -} - -func (tx *Tx) commitFreelist() error { - // Allocate new pages for the new free list. This will overestimate - // the size of the freelist but not underestimate the size (which would be bad). - opgid := tx.meta.pgid - p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1) - if err != nil { - tx.rollback() - return err - } - if err := tx.db.freelist.write(p); err != nil { - tx.rollback() - return err - } - tx.meta.freelist = p.id - // If the high water mark has moved up then attempt to grow the database. - if tx.meta.pgid > opgid { - if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil { - tx.rollback() - return err - } - } - - return nil -} - -// Rollback closes the transaction and ignores all previous updates. Read-only -// transactions must be rolled back and not committed. -func (tx *Tx) Rollback() error { - _assert(!tx.managed, "managed tx rollback not allowed") - if tx.db == nil { - return ErrTxClosed - } - tx.rollback() - return nil -} - -func (tx *Tx) rollback() { - if tx.db == nil { - return - } - if tx.writable { - tx.db.freelist.rollback(tx.meta.txid) - tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist)) - } - tx.close() -} - -func (tx *Tx) close() { - if tx.db == nil { - return - } - if tx.writable { - // Grab freelist stats. - var freelistFreeN = tx.db.freelist.free_count() - var freelistPendingN = tx.db.freelist.pending_count() - var freelistAlloc = tx.db.freelist.size() - - // Remove transaction ref & writer lock. - tx.db.rwtx = nil - tx.db.rwlock.Unlock() - - // Merge statistics. - tx.db.statlock.Lock() - tx.db.stats.FreePageN = freelistFreeN - tx.db.stats.PendingPageN = freelistPendingN - tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize - tx.db.stats.FreelistInuse = freelistAlloc - tx.db.stats.TxStats.add(&tx.stats) - tx.db.statlock.Unlock() - } else { - tx.db.removeTx(tx) - } - - // Clear all references. - tx.db = nil - tx.meta = nil - tx.root = Bucket{tx: tx} - tx.pages = nil -} - -// Copy writes the entire database to a writer. -// This function exists for backwards compatibility. -// -// Deprecated; Use WriteTo() instead. -func (tx *Tx) Copy(w io.Writer) error { - _, err := tx.WriteTo(w) - return err -} - -// WriteTo writes the entire database to a writer. -// If err == nil then exactly tx.Size() bytes will be written into the writer. -func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) { - // Attempt to open reader with WriteFlag - f, err := os.OpenFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0) - if err != nil { - return 0, err - } - defer func() { - if cerr := f.Close(); err == nil { - err = cerr - } - }() - - // Generate a meta page. We use the same page data for both meta pages. - buf := make([]byte, tx.db.pageSize) - page := (*page)(unsafe.Pointer(&buf[0])) - page.flags = metaPageFlag - *page.meta() = *tx.meta - - // Write meta 0. - page.id = 0 - page.meta().checksum = page.meta().sum64() - nn, err := w.Write(buf) - n += int64(nn) - if err != nil { - return n, fmt.Errorf("meta 0 copy: %s", err) - } - - // Write meta 1 with a lower transaction id. - page.id = 1 - page.meta().txid -= 1 - page.meta().checksum = page.meta().sum64() - nn, err = w.Write(buf) - n += int64(nn) - if err != nil { - return n, fmt.Errorf("meta 1 copy: %s", err) - } - - // Move past the meta pages in the file. - if _, err := f.Seek(int64(tx.db.pageSize*2), io.SeekStart); err != nil { - return n, fmt.Errorf("seek: %s", err) - } - - // Copy data pages. - wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2)) - n += wn - if err != nil { - return n, err - } - - return n, nil -} - -// CopyFile copies the entire database to file at the given path. -// A reader transaction is maintained during the copy so it is safe to continue -// using the database while a copy is in progress. -func (tx *Tx) CopyFile(path string, mode os.FileMode) error { - f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode) - if err != nil { - return err - } - - err = tx.Copy(f) - if err != nil { - _ = f.Close() - return err - } - return f.Close() -} - -// Check performs several consistency checks on the database for this transaction. -// An error is returned if any inconsistency is found. -// -// It can be safely run concurrently on a writable transaction. However, this -// incurs a high cost for large databases and databases with a lot of subbuckets -// because of caching. This overhead can be removed if running on a read-only -// transaction, however, it is not safe to execute other writer transactions at -// the same time. -func (tx *Tx) Check() <-chan error { - ch := make(chan error) - go tx.check(ch) - return ch -} - -func (tx *Tx) check(ch chan error) { - // Force loading free list if opened in ReadOnly mode. - tx.db.loadFreelist() - - // Check if any pages are double freed. - freed := make(map[pgid]bool) - all := make([]pgid, tx.db.freelist.count()) - tx.db.freelist.copyall(all) - for _, id := range all { - if freed[id] { - ch <- fmt.Errorf("page %d: already freed", id) - } - freed[id] = true - } - - // Track every reachable page. - reachable := make(map[pgid]*page) - reachable[0] = tx.page(0) // meta0 - reachable[1] = tx.page(1) // meta1 - if tx.meta.freelist != pgidNoFreelist { - for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ { - reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist) - } - } - - // Recursively check buckets. - tx.checkBucket(&tx.root, reachable, freed, ch) - - // Ensure all pages below high water mark are either reachable or freed. - for i := pgid(0); i < tx.meta.pgid; i++ { - _, isReachable := reachable[i] - if !isReachable && !freed[i] { - ch <- fmt.Errorf("page %d: unreachable unfreed", int(i)) - } - } - - // Close the channel to signal completion. - close(ch) -} - -func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool, ch chan error) { - // Ignore inline buckets. - if b.root == 0 { - return - } - - // Check every page used by this bucket. - b.tx.forEachPage(b.root, 0, func(p *page, _ int) { - if p.id > tx.meta.pgid { - ch <- fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid)) - } - - // Ensure each page is only referenced once. - for i := pgid(0); i <= pgid(p.overflow); i++ { - var id = p.id + i - if _, ok := reachable[id]; ok { - ch <- fmt.Errorf("page %d: multiple references", int(id)) - } - reachable[id] = p - } - - // We should only encounter un-freed leaf and branch pages. - if freed[p.id] { - ch <- fmt.Errorf("page %d: reachable freed", int(p.id)) - } else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 { - ch <- fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ()) - } - }) - - // Check each bucket within this bucket. - _ = b.ForEach(func(k, v []byte) error { - if child := b.Bucket(k); child != nil { - tx.checkBucket(child, reachable, freed, ch) - } - return nil - }) -} - -// allocate returns a contiguous block of memory starting at a given page. -func (tx *Tx) allocate(count int) (*page, error) { - p, err := tx.db.allocate(tx.meta.txid, count) - if err != nil { - return nil, err - } - - // Save to our page cache. - tx.pages[p.id] = p - - // Update statistics. - tx.stats.PageCount += count - tx.stats.PageAlloc += count * tx.db.pageSize - - return p, nil -} - -// write writes any dirty pages to disk. -func (tx *Tx) write() error { - // Sort pages by id. - pages := make(pages, 0, len(tx.pages)) - for _, p := range tx.pages { - pages = append(pages, p) - } - // Clear out page cache early. - tx.pages = make(map[pgid]*page) - sort.Sort(pages) - - // Write pages to disk in order. - for _, p := range pages { - size := (int(p.overflow) + 1) * tx.db.pageSize - offset := int64(p.id) * int64(tx.db.pageSize) - - // Write out page in "max allocation" sized chunks. - ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p)) - for { - // Limit our write to our max allocation size. - sz := size - if sz > maxAllocSize-1 { - sz = maxAllocSize - 1 - } - - // Write chunk to disk. - buf := ptr[:sz] - if _, err := tx.db.ops.writeAt(buf, offset); err != nil { - return err - } - - // Update statistics. - tx.stats.Write++ - - // Exit inner for loop if we've written all the chunks. - size -= sz - if size == 0 { - break - } - - // Otherwise move offset forward and move pointer to next chunk. - offset += int64(sz) - ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz])) - } - } - - // Ignore file sync if flag is set on DB. - if !tx.db.NoSync || IgnoreNoSync { - if err := fdatasync(tx.db); err != nil { - return err - } - } - - // Put small pages back to page pool. - for _, p := range pages { - // Ignore page sizes over 1 page. - // These are allocated using make() instead of the page pool. - if int(p.overflow) != 0 { - continue - } - - buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize] - - // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1 - for i := range buf { - buf[i] = 0 - } - tx.db.pagePool.Put(buf) - } - - return nil -} - -// writeMeta writes the meta to the disk. -func (tx *Tx) writeMeta() error { - // Create a temporary buffer for the meta page. - buf := make([]byte, tx.db.pageSize) - p := tx.db.pageInBuffer(buf, 0) - tx.meta.write(p) - - // Write the meta page to file. - if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil { - return err - } - if !tx.db.NoSync || IgnoreNoSync { - if err := fdatasync(tx.db); err != nil { - return err - } - } - - // Update statistics. - tx.stats.Write++ - - return nil -} - -// page returns a reference to the page with a given id. -// If page has been written to then a temporary buffered page is returned. -func (tx *Tx) page(id pgid) *page { - // Check the dirty pages first. - if tx.pages != nil { - if p, ok := tx.pages[id]; ok { - return p - } - } - - // Otherwise return directly from the mmap. - return tx.db.page(id) -} - -// forEachPage iterates over every page within a given page and executes a function. -func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) { - p := tx.page(pgid) - - // Execute function. - fn(p, depth) - - // Recursively loop over children. - if (p.flags & branchPageFlag) != 0 { - for i := 0; i < int(p.count); i++ { - elem := p.branchPageElement(uint16(i)) - tx.forEachPage(elem.pgid, depth+1, fn) - } - } -} - -// Page returns page information for a given page number. -// This is only safe for concurrent use when used by a writable transaction. -func (tx *Tx) Page(id int) (*PageInfo, error) { - if tx.db == nil { - return nil, ErrTxClosed - } else if pgid(id) >= tx.meta.pgid { - return nil, nil - } - - // Build the page info. - p := tx.db.page(pgid(id)) - info := &PageInfo{ - ID: id, - Count: int(p.count), - OverflowCount: int(p.overflow), - } - - // Determine the type (or if it's free). - if tx.db.freelist.freed(pgid(id)) { - info.Type = "free" - } else { - info.Type = p.typ() - } - - return info, nil -} - -// TxStats represents statistics about the actions performed by the transaction. -type TxStats struct { - // Page statistics. - PageCount int // number of page allocations - PageAlloc int // total bytes allocated - - // Cursor statistics. - CursorCount int // number of cursors created - - // Node statistics - NodeCount int // number of node allocations - NodeDeref int // number of node dereferences - - // Rebalance statistics. - Rebalance int // number of node rebalances - RebalanceTime time.Duration // total time spent rebalancing - - // Split/Spill statistics. - Split int // number of nodes split - Spill int // number of nodes spilled - SpillTime time.Duration // total time spent spilling - - // Write statistics. - Write int // number of writes performed - WriteTime time.Duration // total time spent writing to disk -} - -func (s *TxStats) add(other *TxStats) { - s.PageCount += other.PageCount - s.PageAlloc += other.PageAlloc - s.CursorCount += other.CursorCount - s.NodeCount += other.NodeCount - s.NodeDeref += other.NodeDeref - s.Rebalance += other.Rebalance - s.RebalanceTime += other.RebalanceTime - s.Split += other.Split - s.Spill += other.Spill - s.SpillTime += other.SpillTime - s.Write += other.Write - s.WriteTime += other.WriteTime -} - -// Sub calculates and returns the difference between two sets of transaction stats. -// This is useful when obtaining stats at two different points and time and -// you need the performance counters that occurred within that time span. -func (s *TxStats) Sub(other *TxStats) TxStats { - var diff TxStats - diff.PageCount = s.PageCount - other.PageCount - diff.PageAlloc = s.PageAlloc - other.PageAlloc - diff.CursorCount = s.CursorCount - other.CursorCount - diff.NodeCount = s.NodeCount - other.NodeCount - diff.NodeDeref = s.NodeDeref - other.NodeDeref - diff.Rebalance = s.Rebalance - other.Rebalance - diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime - diff.Split = s.Split - other.Split - diff.Spill = s.Spill - other.Spill - diff.SpillTime = s.SpillTime - other.SpillTime - diff.Write = s.Write - other.Write - diff.WriteTime = s.WriteTime - other.WriteTime - return diff -} diff --git a/vendor/github.com/coreos/bbolt/tx_test.go b/vendor/github.com/coreos/bbolt/tx_test.go deleted file mode 100644 index de92cb5..0000000 --- a/vendor/github.com/coreos/bbolt/tx_test.go +++ /dev/null @@ -1,869 +0,0 @@ -package bolt_test - -import ( - "bytes" - "errors" - "fmt" - "log" - "os" - "testing" - - "github.com/coreos/bbolt" -) - -// TestTx_Check_ReadOnly tests consistency checking on a ReadOnly database. -func TestTx_Check_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.Close() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - readOnlyDB, err := bolt.Open(db.f, 0666, &bolt.Options{ReadOnly: true}) - if err != nil { - t.Fatal(err) - } - defer readOnlyDB.Close() - - tx, err := readOnlyDB.Begin(false) - if err != nil { - t.Fatal(err) - } - // ReadOnly DB will load freelist on Check call. - numChecks := 2 - errc := make(chan error, numChecks) - check := func() { - err, _ := <-tx.Check() - errc <- err - } - // Ensure the freelist is not reloaded and does not race. - for i := 0; i < numChecks; i++ { - go check() - } - for i := 0; i < numChecks; i++ { - if err := <-errc; err != nil { - t.Fatal(err) - } - } -} - -// Ensure that committing a closed transaction returns an error. -func TestTx_Commit_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - if _, err := tx.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - if err := tx.Commit(); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that rolling back a closed transaction returns an error. -func TestTx_Rollback_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - if err := tx.Rollback(); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that committing a read-only transaction returns an error. -func TestTx_Commit_ErrTxNotWritable(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - if err := tx.Commit(); err != bolt.ErrTxNotWritable { - t.Fatal(err) - } -} - -// Ensure that a transaction can retrieve a cursor on the root bucket. -func TestTx_Cursor(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - - if _, err := tx.CreateBucket([]byte("woojits")); err != nil { - t.Fatal(err) - } - - c := tx.Cursor() - if k, v := c.First(); !bytes.Equal(k, []byte("widgets")) { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Next(); !bytes.Equal(k, []byte("woojits")) { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Next(); k != nil { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", k) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that creating a bucket with a read-only transaction returns an error. -func TestTx_CreateBucket_ErrTxNotWritable(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.View(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("foo")) - if err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that creating a bucket on a closed transaction returns an error. -func TestTx_CreateBucket_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - if _, err := tx.CreateBucket([]byte("foo")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that a Tx can retrieve a bucket. -func TestTx_Bucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx retrieving a non-existent key returns nil. -func TestTx_Get_NotFound(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if b.Get([]byte("no_such_key")) != nil { - t.Fatal("expected nil value") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can be created and retrieved. -func TestTx_CreateBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } else if b == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Read the bucket through a separate transaction. - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can be created if it doesn't already exist. -func TestTx_CreateBucketIfNotExists(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - // Create bucket. - if b, err := tx.CreateBucketIfNotExists([]byte("widgets")); err != nil { - t.Fatal(err) - } else if b == nil { - t.Fatal("expected bucket") - } - - // Create bucket again. - if b, err := tx.CreateBucketIfNotExists([]byte("widgets")); err != nil { - t.Fatal(err) - } else if b == nil { - t.Fatal("expected bucket") - } - - return nil - }); err != nil { - t.Fatal(err) - } - - // Read the bucket through a separate transaction. - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure transaction returns an error if creating an unnamed bucket. -func TestTx_CreateBucketIfNotExists_ErrBucketNameRequired(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucketIfNotExists([]byte{}); err != bolt.ErrBucketNameRequired { - t.Fatalf("unexpected error: %s", err) - } - - if _, err := tx.CreateBucketIfNotExists(nil); err != bolt.ErrBucketNameRequired { - t.Fatalf("unexpected error: %s", err) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket cannot be created twice. -func TestTx_CreateBucket_ErrBucketExists(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Create the same bucket again. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != bolt.ErrBucketExists { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket is created with a non-blank name. -func TestTx_CreateBucket_ErrBucketNameRequired(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket(nil); err != bolt.ErrBucketNameRequired { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can be deleted. -func TestTx_DeleteBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create a bucket and add a value. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Delete the bucket and make sure we can't get the value. - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - if tx.Bucket([]byte("widgets")) != nil { - t.Fatal("unexpected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - // Create the bucket again and make sure there's not a phantom value. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); v != nil { - t.Fatalf("unexpected phantom value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket on a closed transaction returns an error. -func TestTx_DeleteBucket_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - if err := tx.DeleteBucket([]byte("foo")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that deleting a bucket with a read-only transaction returns an error. -func TestTx_DeleteBucket_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.View(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("foo")); err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that nothing happens when deleting a bucket that doesn't exist. -func TestTx_DeleteBucket_NotFound(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("widgets")); err != bolt.ErrBucketNotFound { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that no error is returned when a tx.ForEach function does not return -// an error. -func TestTx_ForEach_NoError(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error { - return nil - }); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that an error is returned when a tx.ForEach function returns an error. -func TestTx_ForEach_WithError(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - marker := errors.New("marker") - if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error { - return marker - }); err != marker { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that Tx commit handlers are called after a transaction successfully commits. -func TestTx_OnCommit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var x int - if err := db.Update(func(tx *bolt.Tx) error { - tx.OnCommit(func() { x += 1 }) - tx.OnCommit(func() { x += 2 }) - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } else if x != 3 { - t.Fatalf("unexpected x: %d", x) - } -} - -// Ensure that Tx commit handlers are NOT called after a transaction rolls back. -func TestTx_OnCommit_Rollback(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var x int - if err := db.Update(func(tx *bolt.Tx) error { - tx.OnCommit(func() { x += 1 }) - tx.OnCommit(func() { x += 2 }) - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return errors.New("rollback this commit") - }); err == nil || err.Error() != "rollback this commit" { - t.Fatalf("unexpected error: %s", err) - } else if x != 0 { - t.Fatalf("unexpected x: %d", x) - } -} - -// Ensure that the database can be copied to a file path. -func TestTx_CopyFile(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - path := tempfile() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - return tx.CopyFile(path, 0600) - }); err != nil { - t.Fatal(err) - } - - db2, err := bolt.Open(path, 0600, nil) - if err != nil { - t.Fatal(err) - } - - if err := db2.View(func(tx *bolt.Tx) error { - if v := tx.Bucket([]byte("widgets")).Get([]byte("foo")); !bytes.Equal(v, []byte("bar")) { - t.Fatalf("unexpected value: %v", v) - } - if v := tx.Bucket([]byte("widgets")).Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db2.Close(); err != nil { - t.Fatal(err) - } -} - -type failWriterError struct{} - -func (failWriterError) Error() string { - return "error injected for tests" -} - -type failWriter struct { - // fail after this many bytes - After int -} - -func (f *failWriter) Write(p []byte) (n int, err error) { - n = len(p) - if n > f.After { - n = f.After - err = failWriterError{} - } - f.After -= n - return n, err -} - -// Ensure that Copy handles write errors right. -func TestTx_CopyFile_Error_Meta(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - return tx.Copy(&failWriter{}) - }); err == nil || err.Error() != "meta 0 copy: error injected for tests" { - t.Fatalf("unexpected error: %v", err) - } -} - -// Ensure that Copy handles write errors right. -func TestTx_CopyFile_Error_Normal(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - return tx.Copy(&failWriter{3 * db.Info().PageSize}) - }); err == nil || err.Error() != "error injected for tests" { - t.Fatalf("unexpected error: %v", err) - } -} - -// TestTx_releaseRange ensures db.freePages handles page releases -// correctly when there are transaction that are no longer reachable -// via any read/write transactions and are "between" ongoing read -// transactions, which requires they must be freed by -// freelist.releaseRange. -func TestTx_releaseRange(t *testing.T) { - // Set initial mmap size well beyond the limit we will hit in this - // test, since we are testing with long running read transactions - // and will deadlock if db.grow is triggered. - db := MustOpenWithOption(&bolt.Options{InitialMmapSize: os.Getpagesize() * 100}) - defer db.MustClose() - - bucket := "bucket" - - put := func(key, value string) { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte(bucket)) - if err != nil { - t.Fatal(err) - } - return b.Put([]byte(key), []byte(value)) - }); err != nil { - t.Fatal(err) - } - } - - del := func(key string) { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte(bucket)) - if err != nil { - t.Fatal(err) - } - return b.Delete([]byte(key)) - }); err != nil { - t.Fatal(err) - } - } - - getWithTxn := func(txn *bolt.Tx, key string) []byte { - return txn.Bucket([]byte(bucket)).Get([]byte(key)) - } - - openReadTxn := func() *bolt.Tx { - readTx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - return readTx - } - - checkWithReadTxn := func(txn *bolt.Tx, key string, wantValue []byte) { - value := getWithTxn(txn, key) - if !bytes.Equal(value, wantValue) { - t.Errorf("Wanted value to be %s for key %s, but got %s", wantValue, key, string(value)) - } - } - - rollback := func(txn *bolt.Tx) { - if err := txn.Rollback(); err != nil { - t.Fatal(err) - } - } - - put("k1", "v1") - rtx1 := openReadTxn() - put("k2", "v2") - hold1 := openReadTxn() - put("k3", "v3") - hold2 := openReadTxn() - del("k3") - rtx2 := openReadTxn() - del("k1") - hold3 := openReadTxn() - del("k2") - hold4 := openReadTxn() - put("k4", "v4") - hold5 := openReadTxn() - - // Close the read transactions we established to hold a portion of the pages in pending state. - rollback(hold1) - rollback(hold2) - rollback(hold3) - rollback(hold4) - rollback(hold5) - - // Execute a write transaction to trigger a releaseRange operation in the db - // that will free multiple ranges between the remaining open read transactions, now that the - // holds have been rolled back. - put("k4", "v4") - - // Check that all long running reads still read correct values. - checkWithReadTxn(rtx1, "k1", []byte("v1")) - checkWithReadTxn(rtx2, "k2", []byte("v2")) - rollback(rtx1) - rollback(rtx2) - - // Check that the final state is correct. - rtx7 := openReadTxn() - checkWithReadTxn(rtx7, "k1", nil) - checkWithReadTxn(rtx7, "k2", nil) - checkWithReadTxn(rtx7, "k3", nil) - checkWithReadTxn(rtx7, "k4", []byte("v4")) - rollback(rtx7) -} - -func ExampleTx_Rollback() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Create a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - log.Fatal(err) - } - - // Set a value for a key. - if err := db.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) - }); err != nil { - log.Fatal(err) - } - - // Update the key but rollback the transaction so it never saves. - tx, err := db.Begin(true) - if err != nil { - log.Fatal(err) - } - b := tx.Bucket([]byte("widgets")) - if err := b.Put([]byte("foo"), []byte("baz")); err != nil { - log.Fatal(err) - } - if err := tx.Rollback(); err != nil { - log.Fatal(err) - } - - // Ensure that our original value is still set. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value for 'foo' is still: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value for 'foo' is still: bar -} - -func ExampleTx_CopyFile() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Create a bucket and a key. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Copy the database to another file. - toFile := tempfile() - if err := db.View(func(tx *bolt.Tx) error { - return tx.CopyFile(toFile, 0666) - }); err != nil { - log.Fatal(err) - } - defer os.Remove(toFile) - - // Open the cloned database. - db2, err := bolt.Open(toFile, 0666, nil) - if err != nil { - log.Fatal(err) - } - - // Ensure that the key exists in the copy. - if err := db2.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value for 'foo' in the clone is: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - if err := db2.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value for 'foo' in the clone is: bar -} diff --git a/vendor/github.com/deroproject/graviton/const.go b/vendor/github.com/deroproject/graviton/const.go index 4bb9922..ffde962 100644 --- a/vendor/github.com/deroproject/graviton/const.go +++ b/vendor/github.com/deroproject/graviton/const.go @@ -3,13 +3,13 @@ package graviton import "errors" const ( - HASHSIZE_BYTES = 32 // we currently are using blake hash which is 256 bits or 32 bytes - HASHSIZE = HASHSIZE_BYTES - HASHSIZE_BITS = HASHSIZE_BYTES * 8 // hash size in bits - MINBLOCK = 512 // max block size excluding value - MAX_KEYSIZE = MINBLOCK - 64 // 64 bytes are reserved, keys are limited to 448 bytes - MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024 // 2GB since we use split files to store data chunks - MAX_VALUE_SIZE = 100 * 1024 * 1024 // values are limited to this size + HASHSIZE_BYTES = 32 // we currently are using blake hash which is 256 bits or 32 bytes + HASHSIZE = HASHSIZE_BYTES + HASHSIZE_BITS = HASHSIZE_BYTES * 8 // hash size in bits + MINBLOCK = 512 // max block size excluding value + MAX_KEYSIZE = MINBLOCK - 64 // 64 bytes are reserved, keys are limited to 448 bytes + MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024 // 2GB since we use split files to store data chunks + MAX_VALUE_SIZE = 100 * 1024 * 1024 // values are limited to this size TREE_NAME_LIMIT = 127 // TREE name cannot be larger than this in bytes ( not in utf8 chars) ) @@ -17,7 +17,7 @@ const internal_MAX_VERSIONS_TO_KEEP = 20 // this many recent versions will be ke const internal_VERSION_RECORD_SIZE = 24 // three uint64 var ( - ErrNotFound = errors.New("leaf not found") + ErrNotFound = errors.New("leaf not found") ErrVersionNotStored = errors.New("no such version") ErrCorruption = errors.New("Data Corruption") ErrNoMoreKeys = errors.New("No more keys exist") diff --git a/vendor/github.com/deroproject/graviton/cursor.go b/vendor/github.com/deroproject/graviton/cursor.go index 9690c81..f11d4c8 100644 --- a/vendor/github.com/deroproject/graviton/cursor.go +++ b/vendor/github.com/deroproject/graviton/cursor.go @@ -140,7 +140,3 @@ try_again: return k, v, fmt.Errorf("unknown node type, corruption") } } - - - - diff --git a/vendor/github.com/deroproject/graviton/extra.go b/vendor/github.com/deroproject/graviton/extra.go index 24fb10c..3f31828 100644 --- a/vendor/github.com/deroproject/graviton/extra.go +++ b/vendor/github.com/deroproject/graviton/extra.go @@ -4,74 +4,73 @@ import "fmt" import "math" import "crypto/rand" - // Random returns a random key,value from the tree, provided a tree has keys // the following are limitations // a tree containing 0 key, value pairs will return err // randomness depends on number of keys, if tree contains only 1 value, it will be ported etc func (t *Tree) Random() (k, v []byte, err error) { - return t.random(t.root) + return t.random(t.root) } func (t *Tree) random(cnode node) (k, v []byte, err error) { - switch node := cnode.(type) { - case *inner: - if node.loaded_partial { // if node is loaded partially, load it fully now - if err = node.loadinnerfromstore(t.store); err != nil { - return - } + switch node := cnode.(type) { + case *inner: + if node.loaded_partial { // if node is loaded partially, load it fully now + if err = node.loadinnerfromstore(t.store); err != nil { + return } - left, right := node.left, node.right - if left != nil && right != nil { // we have an option to choose from left or right randomly - var rbyte [1]byte - if _, err = rand.Read(rbyte[:]);err != nil { - return - } - if rbyte[0] & 1 == 1 { - return t.random(right) // descend further - } - return t.random(left) // descend further - } - - if right != nil { - return t.random(right) // descend further without any option - } - - if left != nil { - return t.random(left) // descend further without any option - } - - // we can only reach here if a tree has both left,right nil, ie an empty tree - err = ErrNoMoreKeys - return - case *leaf: - if node.loaded_partial { // if leaf is loaded partially, load it fully now - if err = node.loadfullleaffromstore(t.store); err != nil { - return - } - } - return node.key, node.value, nil - default: - return k, v, fmt.Errorf("unknown node type, corruption") } + left, right := node.left, node.right + if left != nil && right != nil { // we have an option to choose from left or right randomly + var rbyte [1]byte + if _, err = rand.Read(rbyte[:]); err != nil { + return + } + if rbyte[0]&1 == 1 { + return t.random(right) // descend further + } + return t.random(left) // descend further + } + + if right != nil { + return t.random(right) // descend further without any option + } + + if left != nil { + return t.random(left) // descend further without any option + } + + // we can only reach here if a tree has both left,right nil, ie an empty tree + err = ErrNoMoreKeys + return + case *leaf: + if node.loaded_partial { // if leaf is loaded partially, load it fully now + if err = node.loadfullleaffromstore(t.store); err != nil { + return + } + } + return node.key, node.value, nil + default: + return k, v, fmt.Errorf("unknown node type, corruption") + } } // estimate number of keys that exist in the tree // very crude but only used for use display func (t *Tree) KeyCountEstimate() (count int64) { - c := t.Cursor() + c := t.Cursor() - var depth_array []int - var floatsum float64 - for _, _, err := c.First(); err == nil ; _, _, err = c.Next() { - floatsum += float64( len(c.node_path)) - depth_array = append(depth_array, len(c.node_path)) - if len(depth_array) >= 20 { - break - } + var depth_array []int + var floatsum float64 + for _, _, err := c.First(); err == nil; _, _, err = c.Next() { + floatsum += float64(len(c.node_path)) + depth_array = append(depth_array, len(c.node_path)) + if len(depth_array) >= 20 { + break } - if len(depth_array) <= 4 { - return int64(count) - } - avg := floatsum / float64(len(depth_array)+1) - return int64 ( math.Exp2(avg)) + } + if len(depth_array) <= 4 { + return int64(count) + } + avg := floatsum / float64(len(depth_array)+1) + return int64(math.Exp2(avg)) } diff --git a/vendor/github.com/deroproject/graviton/graph.go b/vendor/github.com/deroproject/graviton/graph.go index fd642a3..ef99c9a 100644 --- a/vendor/github.com/deroproject/graviton/graph.go +++ b/vendor/github.com/deroproject/graviton/graph.go @@ -1,4 +1,4 @@ -//+build ignore +//+build ignore package graviton @@ -6,12 +6,10 @@ import "os" import "fmt" import "bufio" - // this function will export the tree to a dor graph file to understand any issues -func (t *Tree) Graph(fname string) ( err error) { +func (t *Tree) Graph(fname string) (err error) { - - f, err := os.Create(fname) + f, err := os.Create(fname) if err != nil { return } @@ -20,59 +18,56 @@ func (t *Tree) Graph(fname string) ( err error) { w := bufio.NewWriter(f) defer w.Flush() - w.WriteString("digraph graviton_graph { \n") - defer w.WriteString(" \n}\n") + w.WriteString("digraph graviton_graph { \n") + defer w.WriteString(" \n}\n") - t.graph(t.root,w) - return nil + t.graph(t.root, w) + return nil } -func (t *Tree) graph(cnode node, w *bufio.Writer) { - var err error - switch node := cnode.(type) { - case *inner: - if node.loaded_partial { // if node is loaded partially, load it fully now - if err = node.loadinnerfromstore(t.store); err != nil { - return - } +func (t *Tree) graph(cnode node, w *bufio.Writer) { + var err error + switch node := cnode.(type) { + case *inner: + if node.loaded_partial { // if node is loaded partially, load it fully now + if err = node.loadinnerfromstore(t.store); err != nil { + return } - - w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) - hash,_ := node.Hash(t.store) - w.WriteString(fmt.Sprintf("L%x [ fillcolor=%s label = \"L%x\" ];\n", hash, "red", hash)) - w.WriteString(fmt.Sprintf("}\n")) - - left, right := node.left, node.right - - - if right != nil { - rhash,_ := right.Hash(t.store) - w.WriteString(fmt.Sprintf("L%x -> L%x ;\n", hash, rhash)) - t.graph(right,w) // descend further without any option - } - - if left != nil { - lhash,_ := left.Hash(t.store) - w.WriteString(fmt.Sprintf("L%x -> L%x ;\n", hash, lhash)) - t.graph(left,w) // descend further without any option - } - - return - case *leaf: - if node.loaded_partial { // if leaf is loaded partially, load it fully now - if err = node.loadfullleaffromstore(t.store); err != nil { - return - } - } - w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) - hash,_ := node.Hash(t.store) - keyhash := sum(node.key) - w.WriteString(fmt.Sprintf("L%x [ fillcolor=%s label = \"L%x %x\" ];\n", hash, "green", hash ,keyhash)) - w.WriteString(fmt.Sprintf("}\n")) - //return node.key, node.value, nil - default: - panic("unknown node type, corruption") - return } + + w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) + hash, _ := node.Hash(t.store) + w.WriteString(fmt.Sprintf("L%x [ fillcolor=%s label = \"L%x\" ];\n", hash, "red", hash)) + w.WriteString(fmt.Sprintf("}\n")) + + left, right := node.left, node.right + + if right != nil { + rhash, _ := right.Hash(t.store) + w.WriteString(fmt.Sprintf("L%x -> L%x ;\n", hash, rhash)) + t.graph(right, w) // descend further without any option + } + + if left != nil { + lhash, _ := left.Hash(t.store) + w.WriteString(fmt.Sprintf("L%x -> L%x ;\n", hash, lhash)) + t.graph(left, w) // descend further without any option + } + + return + case *leaf: + if node.loaded_partial { // if leaf is loaded partially, load it fully now + if err = node.loadfullleaffromstore(t.store); err != nil { + return + } + } + w.WriteString(fmt.Sprintf("node [ fontsize=12 style=filled ]\n{\n")) + hash, _ := node.Hash(t.store) + keyhash := sum(node.key) + w.WriteString(fmt.Sprintf("L%x [ fillcolor=%s label = \"L%x %x\" ];\n", hash, "green", hash, keyhash)) + w.WriteString(fmt.Sprintf("}\n")) + //return node.key, node.value, nil + default: + panic("unknown node type, corruption") + return + } } - - diff --git a/vendor/github.com/deroproject/graviton/node_inner.go b/vendor/github.com/deroproject/graviton/node_inner.go index a8bb4d5..e549e96 100644 --- a/vendor/github.com/deroproject/graviton/node_inner.go +++ b/vendor/github.com/deroproject/graviton/node_inner.go @@ -135,7 +135,7 @@ func (in *inner) insert(store *Store, n *leaf) error { return err } } - if (tmp.keyhash[0] == n.keyhash[0] && tmp.keyhash == n.keyhash) || in.bit == lastBit { // if its last node, we are overwriting data, so do it, old versions will be accessible using old roots + if (tmp.keyhash[0] == n.keyhash[0] && tmp.keyhash == n.keyhash) || in.bit == lastBit { // if its last node, we are overwriting data, so do it, old versions will be accessible using old roots return tmp.Put(store, n.keyhash, n.value) } @@ -154,7 +154,7 @@ func (in *inner) insert(store *Store, n *leaf) error { return err } } - if (tmp.keyhash[0] == n.keyhash[0] && tmp.keyhash == n.keyhash) || in.bit == lastBit { // if its last node, we are overwriting data, so do it, old versions will be accessible using old roots + if (tmp.keyhash[0] == n.keyhash[0] && tmp.keyhash == n.keyhash) || in.bit == lastBit { // if its last node, we are overwriting data, so do it, old versions will be accessible using old roots return tmp.Put(store, n.keyhash, n.value) } in.left = newInner(in.bit + 1) // otherwise we have enough slack, insert the node diff --git a/vendor/github.com/deroproject/graviton/snapshot.go b/vendor/github.com/deroproject/graviton/snapshot.go index 151fd15..ab36607 100644 --- a/vendor/github.com/deroproject/graviton/snapshot.go +++ b/vendor/github.com/deroproject/graviton/snapshot.go @@ -19,13 +19,12 @@ type Snapshot struct { // note: 0th tree is not stored in disk // also note that commits are being done so versions might be change func (store *Store) LoadSnapshot(version uint64) (*Snapshot, error) { - if !store.version_data_loaded { - if err := store.loadsnapshottablestoram(); err != nil { - return nil, err - } - } + var err error - _, highest_version, findex, fpos := store.findhighestsnapshotinram() // only latest version can be reached from the table + _, highest_version, findex, fpos, err := store.findhighestsnapshotinram() // only latest version can be reached from the table + if err != nil { + return nil, err + } if version > highest_version { return nil, fmt.Errorf("Database highest version: %d you requested %d.Not Possible!!", highest_version, version) } @@ -38,30 +37,18 @@ func (store *Store) LoadSnapshot(version uint64) (*Snapshot, error) { return nil, err } else { return &Snapshot{store: store, version: highest_version, findex: uint32(findex), fpos: uint32(fpos), vroot: vroot}, nil - } } } // user requested an arbitrary version between 1 and highest_version -1 - _, hvroot, err := store.loadrootusingpos(findex, fpos) // load highest version root tree - if err != nil { + if findex, fpos, err = store.ReadVersionData(version); err != nil { return nil, err } - - var key = [512]byte{':', ':'} // now use it to locate specific version tree - done := 2 - done += binary.PutUvarint(key[done:], version) - - eposition, err := hvroot.Get(store, sum(key[:done])) - if err != nil { - return nil, err - } - - findex, fpos = decode(eposition) _, vroot, err := store.loadrootusingpos(findex, fpos) if err != nil { return nil, err } + return &Snapshot{store: store, version: version, findex: findex, fpos: fpos, vroot: vroot}, nil } @@ -91,7 +78,7 @@ func (s *Snapshot) loadTree(key []byte) (tree *Tree, err error) { if position, err = s.vroot.Get(s.store, sum(key)); err == nil { // underscore is first character if bname, root, err = s.store.loadrootusingpos(decode(position)); err == nil { - tree = &Tree{store: s.store, root: root, treename: bname} + tree = &Tree{store: s.store, root: root, treename: bname, snapshot_version: s.version} tree.Hash() } } @@ -99,20 +86,6 @@ func (s *Snapshot) loadTree(key []byte) (tree *Tree, err error) { return tree, err } -func (store *Store) findhighestsnapshotinram() (index int, version uint64, findex, fpos uint32) { - var highest_version uint64 - for i := 0; i < internal_MAX_VERSIONS_TO_KEEP; i++ { - if highest_version < binary.LittleEndian.Uint64(store.version_data[i*internal_VERSION_RECORD_SIZE:]) { - index = i - version = binary.LittleEndian.Uint64(store.version_data[i*internal_VERSION_RECORD_SIZE:]) - findex = uint32(binary.LittleEndian.Uint64(store.version_data[i*internal_VERSION_RECORD_SIZE+8:])) - fpos = uint32(binary.LittleEndian.Uint64(store.version_data[i*internal_VERSION_RECORD_SIZE+16:])) - highest_version = version - } - } - return -} - // Load a versioned tree from the store all trees have there own version number func (s *Snapshot) GetTreeWithVersion(treename string, version uint64) (*Tree, error) { var buf = [512]byte{':'} @@ -122,7 +95,7 @@ func (s *Snapshot) GetTreeWithVersion(treename string, version uint64) (*Tree, e } if version == 0 { - return &Tree{root: newInner(0), treename: treename, store: s.store}, nil + return &Tree{root: newInner(0), treename: treename, store: s.store, snapshot_version: s.version}, nil } done := 1 diff --git a/vendor/github.com/deroproject/graviton/snapshot_test.go b/vendor/github.com/deroproject/graviton/snapshot_test.go index 54bf9b1..16a4c20 100644 --- a/vendor/github.com/deroproject/graviton/snapshot_test.go +++ b/vendor/github.com/deroproject/graviton/snapshot_test.go @@ -1,8 +1,9 @@ package graviton import ( - "io/ioutil" - "os" + "fmt" + // "io/ioutil" + // "os" "testing" "time" @@ -11,6 +12,82 @@ import ( var dddd_ = time.Now() +// this tests the version tree dag +// this loading of versions and whether they can be accessed and then moved forward +func TestSnapshotDAG(t *testing.T) { + + store, err := NewMemStore() + require.NoError(t, err) + + loop_count := uint64(5) + // now lets commit the tree 5 times + for i := uint64(0); i < loop_count; i++ { + + gv, err := store.LoadSnapshot(0) + require.NoError(t, err) + + tree, err := gv.GetTree("root") + require.NoError(t, err) + require.Equal(t, i, tree.snapshot_version) + + key := []byte(fmt.Sprintf("%d", i+1)) + value := []byte(fmt.Sprintf("%d", i+1)) + require.NoError(t, tree.Put(key, value)) + + commit_version, err := Commit(tree) + require.NoError(t, err) + require.Equal(t, i+1, commit_version) + require.Equal(t, i+1, tree.snapshot_version) + require.Equal(t, i+1, tree.GetVersion()) + + } + + for i := uint64(0); i < loop_count; i++ { + + gv, err := store.LoadSnapshot(i + 1) + require.NoError(t, err) + + tree, err := gv.GetTree("root") + require.NoError(t, err) + + for j := uint64(0); j < i; j++ { + key := []byte(fmt.Sprintf("%d", j+1)) + value := []byte(fmt.Sprintf("%d", j+1)) + + value_actual, err := tree.Get(key) + if err != nil { + fmt.Printf("value result failed j %d\n", j) + } + require.NoError(t, err) + require.Equal(t, value, value_actual) + } + } + + gv, err := store.LoadSnapshot(5) + require.NoError(t, err) + + highest_version, err := gv.GetTreeHighestVersion("root") + require.NoError(t, err) + require.Equal(t, uint64(5), highest_version) + + // now lets test we can move past in history + gv, err = store.LoadSnapshot(3) + require.NoError(t, err) + + tree, err := gv.GetTree("root") + require.NoError(t, err) + + key := []byte(fmt.Sprintf("%d", 4)) + value := []byte(fmt.Sprintf("%d", 4)) + require.NoError(t, tree.Put(key, value)) + commit_version, err := Commit(tree) + require.NoError(t, err) + require.Equal(t, uint64(6), commit_version) // 5 version committed earlier + require.Equal(t, uint64(6), tree.snapshot_version) + require.Equal(t, uint64(4), tree.GetVersion()) // tree version should be 4 + +} + // this tests various treename entry points func TestTreeNameLimit(t *testing.T) { @@ -85,21 +162,43 @@ func TestLoadSnapshot(t *testing.T) { _, err = store.LoadSnapshot(99) // trigger version is higher than available error require.Error(t, err) + // now lets commit the tree 5 times + loop_count := uint64(5) + for i := uint64(0); i < loop_count; i++ { + gv, err := store.LoadSnapshot(0) + require.NoError(t, err) + + tree, err := gv.GetTree("root") + require.NoError(t, err) + require.Equal(t, i, tree.snapshot_version) + + key := []byte(fmt.Sprintf("%d", i+1)) + value := []byte(fmt.Sprintf("%d", i+1)) + require.NoError(t, tree.Put(key, value)) + + _, err = Commit(tree) + require.NoError(t, err) + } + //fmt.Printf("error %s\n", store.loadsnapshottablestoram()) - store.version_data[0] = 1 - store.version_data[16] = 1 + store.versionrootfile.memoryfile[(loop_count-1)*8+7] = 1 // corrupt last entry + store.versionrootfile.memoryfile[(loop_count-2)*8+7] = 1 // corrupt second last entry - _, err = store.LoadSnapshot(1) // trigger recent version corruption + _, err = store.LoadSnapshot(0) // trigger recent version corruption require.Error(t, err) - store.version_data[24] = 2 - store.version_data[24+16] = 1 - _, err = store.LoadSnapshot(1) // trigger recent version corruption + _, err = store.LoadSnapshot(4) // trigger second last version corruption require.Error(t, err) + /* + store.version_data[24] = 2 + store.version_data[24+16] = 1 + _, err = store.LoadSnapshot(1) // trigger recent version corruption + require.Error(t, err) - _, _, err = store.write([]byte{3, 0, 0, 0}) // write empty inner record - _, err = store.LoadSnapshot(1) // trigger recent version corruption - require.Error(t, err) + _, _, err = store.write([]byte{3, 0, 0, 0}) // write empty inner record + _, err = store.LoadSnapshot(1) // trigger recent version corruption + require.Error(t, err) + */ // create a complex error, where deep error is created using internal structures store, err = NewMemStore() @@ -118,54 +217,4 @@ func TestLoadSnapshot(t *testing.T) { gv, err = store.LoadSnapshot(0) require.NoError(t, err) - eposition, err := gv.vroot.Get(store, sum([]byte{':', ':', 1})) - require.NoError(t, err) - - _, fpos := decode(eposition) - - // lets overwrite the file with with corrupt inner node - file := store.files[0] - //file.fileh.WriteAt([]byte{3, 5, 99, 0}, int64(fpos)) - copy(file.memoryfile[fpos:], []byte{3, 5, 99, 0}) - _, err = store.LoadSnapshot(1) // trigger recent version corruption - require.Error(t, err) -} - -func TestIloadSnapshottablestoram(t *testing.T) { - //store, err := NewMemStore() - - dir, err := ioutil.TempDir("", "example") - require.NoError(t, err) - defer os.RemoveAll(dir) // clean up - - store, err := NewDiskStore(dir) // make file handles unlimited - require.NoError(t, err) - gv, err := store.LoadSnapshot(0) - require.NoError(t, err) - store.Close() - store.version_data_loaded = false - - gv, err = store.LoadSnapshot(1) - require.Error(t, err) // this root does not exist - - // second error - dir2, err := ioutil.TempDir("", "example") - require.NoError(t, err) - defer os.RemoveAll(dir2) // clean up - store, err = NewDiskStore(dir2) // make file handles unlimited - require.NoError(t, err) - gv, err = store.LoadSnapshot(0) - require.NoError(t, err) - tree, err := gv.GetTree("root") - require.NoError(t, err) - - tree.Put([]byte{byte(0)}, []byte{byte(0)}) - require.NoError(t, tree.Commit()) - tree.Put([]byte{byte(1)}, []byte{byte(1)}) - require.NoError(t, tree.Commit()) - store.versionrootfile.diskfile.Truncate(510) - store.version_data_loaded = false - gv, err = store.LoadSnapshot(1) - require.Error(t, err) // this root does not exist - } diff --git a/vendor/github.com/deroproject/graviton/special.go b/vendor/github.com/deroproject/graviton/special.go index 880baa6..3ec5430 100644 --- a/vendor/github.com/deroproject/graviton/special.go +++ b/vendor/github.com/deroproject/graviton/special.go @@ -5,54 +5,58 @@ package graviton import "golang.org/x/xerrors" - // we only have a keyhash and need to get both the key,value -func (t *Tree) GetKeyValue(keyhash [HASHSIZE]byte) (int,[]byte,[]byte, error) { - return t.root.GetKeyValue(t.store, keyhash,256,0 ) +func (t *Tree) GetKeyValue(keyhash [HASHSIZE]byte) (int, []byte, []byte, error) { + return t.root.GetKeyValue(t.store, keyhash, 256, 0) } -func (in *inner) GetKeyValue(store *Store, keyhash [HASHSIZE]byte, valid_bit_count,used_bit_count int) (int,[]byte,[]byte, error) { +func (in *inner) GetKeyValue(store *Store, keyhash [HASHSIZE]byte, valid_bit_count, used_bit_count int) (int, []byte, []byte, error) { if err := in.load_partial(store); err != nil { // if inner node is loaded partially, load it fully now - return used_bit_count,nil,nil, err + return used_bit_count, nil, nil, err } - if used_bit_count > valid_bit_count || valid_bit_count <= 0 { - return used_bit_count,nil,nil, xerrors.Errorf("%w: right dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) - } + if used_bit_count > valid_bit_count || valid_bit_count <= 0 { + return used_bit_count, nil, nil, xerrors.Errorf("%w: right dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) + } if isBitSet(keyhash[:], uint(in.bit)) { if in.right == nil { - return used_bit_count,nil,nil, xerrors.Errorf("%w: right dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) + return used_bit_count, nil, nil, xerrors.Errorf("%w: right dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) } - switch in.right.(type) { // draw left branch - case *inner: return in.right.(*inner).GetKeyValue(store, keyhash,valid_bit_count,used_bit_count+1) - case *leaf: return in.right.(*leaf).GetKeyValue(store, keyhash,valid_bit_count,used_bit_count+1) - default: panic("unknown node type") - } - + switch in.right.(type) { // draw left branch + case *inner: + return in.right.(*inner).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) + case *leaf: + return in.right.(*leaf).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) + default: + panic("unknown node type") + } + } if in.left == nil { - return used_bit_count,nil,nil, xerrors.Errorf("%w: left dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) + return used_bit_count, nil, nil, xerrors.Errorf("%w: left dead end at %d. keyhash %x", ErrNotFound, in.bit, keyhash) } switch in.left.(type) { // draw left branch - case *inner: return in.left.(*inner).GetKeyValue(store, keyhash,valid_bit_count,used_bit_count+1) - case *leaf: return in.left.(*leaf).GetKeyValue(store, keyhash,valid_bit_count,used_bit_count+1) - default: panic("unknown node type") + case *inner: + return in.left.(*inner).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) + case *leaf: + return in.left.(*leaf).GetKeyValue(store, keyhash, valid_bit_count, used_bit_count+1) + default: + panic("unknown node type") } } // should we return a copy -func (l *leaf) GetKeyValue(store *Store, keyhash [HASHSIZE]byte,valid_bit_count,used_bit_count int) (int,[]byte, []byte, error) { +func (l *leaf) GetKeyValue(store *Store, keyhash [HASHSIZE]byte, valid_bit_count, used_bit_count int) (int, []byte, []byte, error) { if l.loaded_partial { // if leaf is loaded partially, load it fully now if err := l.loadfullleaffromstore(store); err != nil { - return used_bit_count,nil,nil, err + return used_bit_count, nil, nil, err } } if l.keyhash == keyhash { - return used_bit_count,l.key,l.value, nil + return used_bit_count, l.key, l.value, nil } - return used_bit_count,nil,nil, xerrors.Errorf("%w: collision, keyhash %x not found", ErrNotFound, keyhash) + return used_bit_count, nil, nil, xerrors.Errorf("%w: collision, keyhash %x not found", ErrNotFound, keyhash) } - diff --git a/vendor/github.com/deroproject/graviton/store.go b/vendor/github.com/deroproject/graviton/store.go index 6e4816c..98b9152 100644 --- a/vendor/github.com/deroproject/graviton/store.go +++ b/vendor/github.com/deroproject/graviton/store.go @@ -38,11 +38,7 @@ type Store struct { files map[uint32]*file findex uint32 - versionrootfile *file // only maintains recent version records - - version_index int // version index to rotate inside version data - version_data [512]byte // stores version data pointers, 20 * 24 , each record is 24 bytes - version_data_loaded bool // whether the version data loaded + versionrootfile *file // only maintains recent version records, each version is 8 bytes and stores the file index and fpos //internal_value_root *inner // internal append only value root commitsync sync.RWMutex // used to sync altroots value root, versioned root @@ -270,72 +266,84 @@ func (s *Store) read(findex, fpos uint32, buf []byte) (int, error) { } +// versions are 1 based + func (s *Store) writeVersionData(version uint64, findex, fpos uint32) error { var buf [512]byte s.discsync.Lock() defer s.discsync.Unlock() - copy(buf[:], s.version_data[:]) - index := (s.version_index + 1) % internal_MAX_VERSIONS_TO_KEEP - binary.LittleEndian.PutUint64(buf[index*internal_VERSION_RECORD_SIZE+0:], version) - binary.LittleEndian.PutUint64(buf[index*internal_VERSION_RECORD_SIZE+8:], uint64(findex)) - binary.LittleEndian.PutUint64(buf[index*internal_VERSION_RECORD_SIZE+16:], uint64(fpos)) + binary.LittleEndian.PutUint32(buf[0:], findex) + binary.LittleEndian.PutUint32(buf[4:], fpos) + version-- if s.storage_layer == disk { - if _, err := s.versionrootfile.diskfile.WriteAt(buf[:], 0); err != nil { + if _, err := s.versionrootfile.diskfile.WriteAt(buf[:8], int64(version*8)); err != nil { return err } } else if s.storage_layer == memory { - s.versionrootfile.memoryfile = append(s.versionrootfile.memoryfile[:0], buf[:]...) + if uint64(len(s.versionrootfile.memoryfile)) <= (version+1)*8 { + s.versionrootfile.memoryfile = append(s.versionrootfile.memoryfile, []byte{0, 0, 0, 0, 0, 0, 0, 0}...) + } + copy(s.versionrootfile.memoryfile[version*8:], buf[:8]) } else { return fmt.Errorf("unknown storage layer") } - copy(s.version_data[:], buf[:]) - s.version_index = index return nil - } -// load recent snapshot list to ram -func (s *Store) loadsnapshottablestoram() (err error) { +// versions are 1 based +func (s *Store) ReadVersionData(version uint64) (findex uint32, fpos uint32, err error) { var buf [512]byte + s.discsync.Lock() + defer s.discsync.Unlock() + + version-- if s.storage_layer == disk { - if finfo, err := s.versionrootfile.diskfile.Stat(); err == nil { // if newly created file, it return 0 - if finfo.Size() == 0 { - copy(s.version_data[:], buf[:]) - s.version_data_loaded = true - return nil - } + if _, err := s.versionrootfile.diskfile.ReadAt(buf[:8], int64(version*8)); err != nil { + return 0, 0, err } else { - return err + findex = binary.LittleEndian.Uint32(buf[0:]) + fpos = binary.LittleEndian.Uint32(buf[4:]) } + } else if s.storage_layer == memory { - if len(s.versionrootfile.memoryfile) == 0 { - copy(s.version_data[:], buf[:]) - s.version_data_loaded = true - return nil + if uint64(len(s.versionrootfile.memoryfile)) <= (version)*8 { + return 0, 0, fmt.Errorf("invalid version %d %d", version, len(s.versionrootfile.memoryfile)) + } else { + findex = binary.LittleEndian.Uint32(s.versionrootfile.memoryfile[version*8+0:]) + fpos = binary.LittleEndian.Uint32(s.versionrootfile.memoryfile[version*8+4:]) } } else { - return fmt.Errorf("unknown storage layer") + return 0, 0, fmt.Errorf("unknown storage layer") } - - var bytes_count int - - if s.storage_layer == disk { - bytes_count, err = s.versionrootfile.diskfile.ReadAt(buf[:], 0) - } else if s.storage_layer == memory { - bytes_count = copy(buf[:], s.versionrootfile.memoryfile) - } - - if bytes_count == 512 { - copy(s.version_data[:], buf[:]) - s.version_data_loaded = true - s.version_index, _, _, _ = s.findhighestsnapshotinram() // setup index properly - return nil - } - - return err + return +} + +func (s *Store) findhighestsnapshotinram() (index int, version uint64, findex, fpos uint32, err error) { + if s.storage_layer == disk { + var fstat os.FileInfo + if fstat, err = s.versionrootfile.diskfile.Stat(); err != nil { + return + } + if version = uint64(fstat.Size() / 8); version == 0 { + return + } + findex, fpos, err = s.ReadVersionData(version) + + } else if s.storage_layer == memory { + version = uint64(len(s.versionrootfile.memoryfile) / 8) + if version == 0 { + return + } + + findex, fpos, err = s.ReadVersionData(version) + } else { + err = fmt.Errorf("unknown storage layer") + } + + return } diff --git a/vendor/github.com/deroproject/graviton/store_test.go b/vendor/github.com/deroproject/graviton/store_test.go index 79d8429..fea3f54 100644 --- a/vendor/github.com/deroproject/graviton/store_test.go +++ b/vendor/github.com/deroproject/graviton/store_test.go @@ -316,21 +316,34 @@ func TestPersistantStore_Empty(t *testing.T) { require.Panics(t, func() { emptystore.uint_to_filename(0) }) // memory store cannot translate filenames emptystore.storage_layer = unknown_layer - require.Error(t, emptystore.loadfiles()) // files cannot be loaded from unknown layer - require.Error(t, emptystore.loadsnapshottablestoram()) // snapshot table cannot eb loaded from unknown layer - emptystore.storage_layer = memory - emptystore.versionrootfile = &file{memoryfile: make([]byte, 512, 512)} - require.NoError(t, emptystore.loadsnapshottablestoram()) + require.Error(t, emptystore.loadfiles()) // files cannot be loaded from unknown layer emptystore.storage_layer = unknown_layer require.Error(t, emptystore.writeVersionData(0, 0, 0)) // unknown cannot write version data + _, err := emptystore.LoadSnapshot(0) // unknown storage layer cannot give verions + require.Error(t, err) - //emptystore.storage_layer = memory - //emptystore.versionrootfile = &file{} - //require.Error(t,emptystore.writeVersionData(0,0,0)) // unknown cannot write version data + _, _, err = emptystore.ReadVersionData(99) // unknown cannot read version data + require.Error(t, err) + + { + store, err := NewMemStore() + _, _, err = store.ReadVersionData(99) // cannot read future version from memory + require.Error(t, err) + } + + { + dir, err := ioutil.TempDir("", "example99") + require.NoError(t, err) + defer os.RemoveAll(dir) // clean up + store, err := NewDiskStore(dir) + + _, _, err = store.ReadVersionData(99) // cannot read future version from memory + require.Error(t, err) + } emptystore.storage_layer = unknown_layer - _, err := emptystore.read(0, 0, nil) + _, err = emptystore.read(0, 0, nil) require.Error(t, err) // unknown cannot read data store, err := NewMemStore() diff --git a/vendor/github.com/deroproject/graviton/tree.go b/vendor/github.com/deroproject/graviton/tree.go index c78b9b1..1555a21 100644 --- a/vendor/github.com/deroproject/graviton/tree.go +++ b/vendor/github.com/deroproject/graviton/tree.go @@ -21,6 +21,8 @@ type Tree struct { size int Tags []string // tags used while commit, will get cleaned after commit + snapshot_version uint64 // used to track which snapshot version this tree has loaded from + tmp_buffer bytes.Buffer } @@ -109,37 +111,34 @@ func Commit(trees ...*Tree) (committed_version uint64, err error) { trees[0].store.commitsync.Lock() defer trees[0].store.commitsync.Unlock() - gv, err := trees[0].store.LoadSnapshot(0) + // sanity checkthat all trees were derived from the same snapshot + first_tree_snapshot_version := trees[0].snapshot_version + for i := range trees { + if first_tree_snapshot_version != trees[i].snapshot_version { + return 0, fmt.Errorf("all trees simultaneously committed must be derived from the same snapshot") + } + } + + gv, err := trees[0].store.LoadSnapshot(first_tree_snapshot_version) if err != nil { return } - for _, tree := range trees { + for _, tree := range trees { // commit all the trees with reference to same snapshot if err = gv.commit(tree); err != nil { return } } - // version should be committed only if it has changed - // this block of code writes reverse version pointers - _, highest_version, findex, fpos := trees[0].store.findhighestsnapshotinram() - var valuearray [HASHSIZE]byte - var key [512]byte - key[0] = ':' - key[1] = ':' - done := 2 - done += binary.PutUvarint(key[done:], highest_version) - - valuesize := encode(findex, fpos, valuearray[:]) //store link of previous version root to previous version findex,fpos - - if err = gv.vroot.Insert(gv.store, newLeaf(sum([]byte(key[:done])), []byte(key[:done]), valuearray[:valuesize])); err == nil { - if findex, fpos, err = trees[0].commit_inner(gv, true, 0, gv.vroot); err == nil { // we must discard any version changes - if err = trees[0].store.writeVersionData(gv.vroot.version_current, findex, fpos); err == nil { - committed_version = gv.vroot.version_current + var findex, fpos uint32 + if findex, fpos, err = trees[0].commit_inner(gv, true, 0, gv.vroot); err == nil { // version number increments here + if err = trees[0].store.writeVersionData(gv.vroot.version_current, findex, fpos); err == nil { + committed_version = gv.vroot.version_current + for i := range trees { + trees[i].snapshot_version = committed_version // increment version } } } - //fmt.Printf("committing version tree %x\n", gv.vroot.Hash(gv.store)) // this is we are cleaning up the trees, should we report bak any error , why should this code be here @@ -323,7 +322,8 @@ func (t *Tree) commit_inner(gv *Snapshot, specialversion bool, level int, in *in if specialversion { // this is for the version root // lets increment the version number and put it again - _, in.version_current, _, _ = t.store.findhighestsnapshotinram() // setup index properly + + _, in.version_current, _, _, _ = t.store.findhighestsnapshotinram() // setup index properly in.version_current++ in.version_previous = old_version diff --git a/vendor/github.com/deroproject/graviton/tree_test.go b/vendor/github.com/deroproject/graviton/tree_test.go index e90a6a9..c4a6639 100644 --- a/vendor/github.com/deroproject/graviton/tree_test.go +++ b/vendor/github.com/deroproject/graviton/tree_test.go @@ -230,8 +230,7 @@ func TestDiscard(t *testing.T) { tree.Put([]byte{46}, []byte{89}) // tree is dirty now require.Equal(t, true, tree.IsDirty()) - store.versionrootfile.diskfile.Truncate(510) - store.version_data_loaded = false + store.versionrootfile.diskfile.Truncate(0) require.Error(t, tree.Discard()) } @@ -281,11 +280,11 @@ func TestCommits(t *testing.T) { require.NoError(t, tree.Commit()) //create err - store.versionrootfile.diskfile.Truncate(510) // version file has been damaged - store.version_data_loaded = false + //store.versionrootfile.diskfile.Truncate(510) // version file has been damaged + //store.version_data_loaded = false - tree.Put([]byte{45}, []byte{80}) - require.Error(t, tree.Commit()) + //tree.Put([]byte{45}, []byte{80}) + //require.Error(t, tree.Commit()) } @@ -312,11 +311,11 @@ func TestCommits_rarecase(t *testing.T) { //tree.Put([]byte{45}, []byte{80}) //create err - store.versionrootfile.diskfile.Truncate(510) // version file has been damaged - store.version_data_loaded = false + //store.versionrootfile.diskfile.Truncate(510) // version file has been damaged + //store.version_data_loaded = false - _, _, err = tree.commit_inner(gv, false, 0, tree.root) - require.Error(t, err) + //_, _, err = tree.commit_inner(gv, false, 0, tree.root) + //require.Error(t, err) // this is to test a condition which will probably never occur until disk is corrupted @@ -486,3 +485,50 @@ func TestCommitinner(t *testing.T) { _, _, err = tree.commit_inner(gv, false, 0, tree.root) require.Error(t, err) } + +func TestMultiCommits(t *testing.T) { + store, err := NewMemStore() + //store, err := NewDiskStore("/tmp/test") // make file handles are unlimited + require.NoError(t, err) + + gv0, err := store.LoadSnapshot(0) + require.NoError(t, err) + + tree1, err := gv0.GetTree("root1") + require.NoError(t, err) + tree2, err := gv0.GetTree("root2") + require.NoError(t, err) + tree1.Put([]byte{byte(1)}, []byte{byte(1)}) + tree2.Put([]byte{byte(2)}, []byte{byte(2)}) + _, err = Commit(tree1, tree2) // commit both trees + require.NoError(t, err) + + tree1.Put([]byte{byte(1)}, []byte{byte(1)}) + tree2.Put([]byte{byte(2)}, []byte{byte(2)}) + _, err = Commit(tree1, tree2) // commit both trees + require.NoError(t, err) + + // now lets load the same tree from different snapshots + + gv1, err := store.LoadSnapshot(1) + require.NoError(t, err) + + gv2, err := store.LoadSnapshot(2) + require.NoError(t, err) + + tree1, err = gv1.GetTree("root1") + require.NoError(t, err) + tree2, err = gv2.GetTree("root2") + require.NoError(t, err) + + tree1.Put([]byte{byte(1)}, []byte{byte(1)}) + tree2.Put([]byte{byte(2)}, []byte{byte(2)}) + + _, err = Commit(tree1, tree2) // commit both trees but an error since both trees are from different snapshot + require.Error(t, err) + + tree1.snapshot_version = 3 // non existant version + err = tree1.Commit() + require.Error(t, err) + +} diff --git a/vendor/github.com/intel-go/cpuid/.gitignore b/vendor/github.com/intel-go/cpuid/.gitignore deleted file mode 100644 index b8bd026..0000000 --- a/vendor/github.com/intel-go/cpuid/.gitignore +++ /dev/null @@ -1,28 +0,0 @@ -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app diff --git a/vendor/github.com/intel-go/cpuid/LICENSE b/vendor/github.com/intel-go/cpuid/LICENSE deleted file mode 100644 index 24b6701..0000000 --- a/vendor/github.com/intel-go/cpuid/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2015, Intel Corporation -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/intel-go/cpuid/README.md b/vendor/github.com/intel-go/cpuid/README.md deleted file mode 100644 index 7783f0f..0000000 --- a/vendor/github.com/intel-go/cpuid/README.md +++ /dev/null @@ -1,244 +0,0 @@ -# cpuid -### Intel CPUID library for Go Programming Language - -The cpuid package provides convenient and fast access to information from -the x86 CPUID instruction. -The package gathers all information during package initialization phase -so its public interface will not need to execute the CPUID instruction at runtime. -Frequent calls to the CPUID instruction can hurt performance, -so this package makes it easier to do CPU-specific optimizations. - -[![GoDoc](https://godoc.org/github.com/intel-go/cpuid?status.svg)](https://godoc.org/github.com/intel-go/cpuid) - -### You can get it with - -```shell -go get github.com/intel-go/cpuid -``` - -### Example: - -```go -package main - -import ( - "github.com/intel-go/cpuid" - "fmt" -) - -func main() { - fmt.Printf("VendorString: %s\n", cpuid.VendorIdentificatorString) - - fmt.Printf("Features: ") - for i := uint64(0); i < 64; i++ { - if cpuid.HasFeature(1 << i) { - fmt.Printf("%s ", cpuid.FeatureNames[1< **SSE3** Prescott New Instructions-SSE3 (PNI)
- > **PCLMULQDQ** PCLMULQDQ support
- > **DTES64** 64-bit debug store (edx bit 21)
- > **MONITOR** MONITOR and MWAIT instructions (SSE3)
- > **DSI_CPL** CPL qualified debug store
- > **VMX** Virtual Machine eXtensions
- > **SMX** Safer Mode Extensions (LaGrande)
- > **EST** Enhanced SpeedStep
- > **TM2** Thermal Monitor 2
- > **SSSE3** Supplemental SSE3 instructions
- > **CNXT_ID** L1 Context ID
- > **SDBG** Silicon Debug interface
- > **FMA** Fused multiply-add (FMA3)
- > **CX16** CMPXCHG16B instruction
- > **XTPR** Can disable sending task priority messages
- > **PDCM** Perfmon & debug capability
- > **PCID** Process context identifiers (CR4 bit 17)
- > **DCA** Direct cache access for DMA writes[10][11]
- > **SSE4_1** SSE4.1 instructions
- > **SSE4_2** SSE4.2 instructions
- > **X2APIC** x2APIC support
- > **MOVBE** MOVBE instruction (big-endian)
- > **POPCNT** POPCNT instruction
- > **TSC_DEADLINE** line APIC supports one-shot operation using a TSC deadline value
- > **AES** AES instruction set
- > **XSAVE** XSAVE, XRESTOR, XSETBV, XGETBV
- > **OSXSAVE** XSAVE enabled by OS
- > **AVX** Advanced Vector Extensions
- > **F16C** F16C (half-precision) FP support
- > **RDRND** RDRAND (on-chip random number generator) support
- > **HYPERVISOR** Running on a hypervisor (always 0 on a real CPU, but also with some hypervisors)
- > **FPU** Onboard x87 FPU
- > **VME** Virtual 8086 mode extensions (such as VIF, VIP, PIV)
- > **DE** Debugging extensions (CR4 bit 3)
- > **PSE** Page Size Extension
- > **TSC** Time Stamp Counter
- > **MSR** Model-specific registers
- > **PAE** Physical Address Extension
- > **MCE** Machine Check Exception
- > **CX8** CMPXCHG8 (compare-and-swap) instruction
- > **APIC** Onboard Advanced Programmable Interrupt Controller
- > **SEP** SYSENTER and SYSEXIT instructions
- > **MTRR** Memory Type Range Registers
- > **PGE** Page Global Enable bit in CR4
- > **MCA** Machine check architecture
- > **CMOV** Conditional move and FCMOV instructions
- > **PAT** Page Attribute Table
- > **PSE_36** 36-bit page size extension
- > **PSN** Processor Serial Number
- > **CLFSH** CLFLUSH instruction (SSE2)
- > **DS** Debug store: save trace of executed jumps
- > **ACPI** Onboard thermal control MSRs for ACPI
- > **MMX** MMX instructions
- > **FXSR** FXSAVE, FXRESTOR instructions, CR4 bit 9
- > **SSE** SSE instructions (a.k.a. Katmai New Instructions)
- > **SSE2** SSE2 instructions
- > **SS** CPU cache supports self-snoop
- > **HTT** Hyper-threading
- > **TM** Thermal monitor automatically limits temperature
- > **IA64** IA64 processor emulating x86
- > **PBE** Pending Break Enable (PBE# pin) wakeup support
- -Usage example: - -```go -if EnabledAVX && HasFeature(AVX) { - fmt.Printf("We can use AVX\n") -} -``` - -* **func HasExtendedFeature(feature uint64) bool** to check for the following features: - > **FSGSBASE** Access to base of %fs and %gs
- > **IA32_TSC_ADJUST** IA32_TSC_ADJUST MSR is supported if 1
- > **BMI1** Bit Manipulation Instruction Set 1
- > **HLE** Transactional Synchronization Extensions
- > **AVX2** Advanced Vector Extensions 2
- > **SMEP** Supervisor-Mode Execution Prevention
- > **BMI2** Bit Manipulation Instruction Set 2
- > **ERMS** Enhanced REP MOVSB/STOSB
- > **INVPCID** INVPCID instruction
- > **RTM** Transactional Synchronization Extensions
- > **PQM** Supports Platform Quality of Service Monitoring (PQM) capability if 1
- > **DFPUCDS** Deprecates FPU CS and FPU DS values if 1
- > **MPX** Intel MPX (Memory Protection Extensions)
- > **PQE** Supports Platform Quality of Service Enforcement (PQE) capability if 1
- > **AVX512F** AVX-512 Foundation
- > **AVX512DQ** AVX-512 Doubleword and Quadword Instructions
- > **RDSEED** RDSEED instruction
- > **ADX** Intel ADX (Multi-Precision Add-Carry Instruction Extensions)
- > **SMAP** Supervisor Mode Access Prevention
- > **AVX512IFMA** AVX-512 Integer Fused Multiply-Add Instructions
- > **PCOMMIT** PCOMMIT instruction
- > **CLFLUSHOPT** CLFLUSHOPT instruction
- > **CLWB** CLWB instruction
- > **INTEL_PROCESSOR_TRACE** Intel Processor Trace
- > **AVX512PF** AVX-512 Prefetch Instructions
- > **AVX512ER** AVX-512 Exponential and Reciprocal Instructions
- > **AVX512CD** AVX-512 Conflict Detection Instructions
- > **SHA** Intel SHA extensions
- > **AVX512BW** AVX-512 Byte and Word Instructions
- > **AVX512VL** AVX-512 Vector Length Extensions
- > **PREFETCHWT1** PREFETCHWT1 instruction
- > **AVX512VBMI** AVX-512 Vector Bit Manipulation Instructions
- -* **func HasExtraFeature(feature uint64) bool** - > **LAHF_LM** LahfSahf LAHF and SAHF instruction support in 64-bit mod
- > **CMP_LEGACY** CmpLegacy Core multi-processing legacy mode.
- > **SVM** SVM Secure virtual machine.
- > **EXTAPIC** ExtApicSpace Extended APIC space.
- > **CR8_LEGACY** AltMovCr8 LOCK MOV CR0 means MOV CR8.
- > **ABM** ABM Advanced bit manipulation. LZCNT instruction support.
- > **SSE4A** SSE4A EXTRQ, INSERTQ, MOVNTSS, and MOVNTSD instruction support.
- > **MISALIGNSSE** Misaligned SSE mode.
- > **PREFETCHW** PREFETCH and PREFETCHW instruction support.
- > **OSVW** OSVW OS visible workaround. Indicates OS-visible workaround support.
- > **IBS** IBS Instruction based sampling.
- > **XOP** XOP Extended operation support.
- > **SKINIT** SKINIT SKINIT and STGI are supported.
- > **WDT** WDT Watchdog timer support.
- > **LWP** LWP Lightweight profiling support.
- > **FMA4** FMA4 Four-operand FMA instruction support.
- > **TCE** Translation Cache Extension
- > **NODEID_MSR** NodeID MSR
- > **TBM** TBM Trailing bit manipulation instruction support.
- > **TOPOEXT** TopologyExtensio Topology extensions support.
- > **PERFCTR_CORE** PerfCtrExtCore Processor performance counter extensions support.
- > **PERFCTR_NB** PerfCtrExtNB NB performance counter extensions support.
- > **SPM** StreamPerfMon Streaming performance monitor architecture.
- > **DBX** DataBreakpointEx Data access breakpoint extension.
- > **PERFTSC** PerfTsc
- > **PCX_L2I** L2I perf counter extensions
- > **FPU_2** Onboard x87 FPU
- > **VME_2** Virtual mode extensions (VIF)
- > **DE_2** Debugging extensions (CR4 bit 3)
- > **PSE_2** Page Size Extension
- > **TSC_2** Time Stamp Counter
- > **MSR_2** Model-specific register
- > **PAE_2** Physical Address Extension
- > **MCE_2** Machine Check Exception
- > **CX8_2** CMPXCHG8 (compare-and-swap) instruction
- > **APIC_2** Onboard Advanced Programmable Interrupt Controller
- > **SYSCALL** SYSCALL and SYSRET instructions
- > **MTRR_2** Memory Type Range Registers
- > **PGE_2** Page Global Enable bit in CR4
- > **MCA_2** Machine check architecture
- > **CMOV_2** Conditional move and FCMOV instructions
- > **PAT_2** Page Attribute Table
- > **PSE36** 36-bit page size extension
- > **MP** Multiprocessor Capable
- > **NX** NX bit
- > **MMXEXT** Extended MMX
- > **MMX_2** MMX instructions
- > **FXSR_2** FXSAVE, FXRSTOR instructions
- > **FXSR_OPT** FXSAVE/FXRSTOR optimizations
- > **PDPE1GB** Gibibyte pages
- > **RDTSCP** RDTSCP instruction
- > **LM** Long mode
- > **_3DNOWEXT** Extended 3DNow!
- > **_3DNOW** 3DNow!
diff --git a/vendor/github.com/intel-go/cpuid/cpuid.go b/vendor/github.com/intel-go/cpuid/cpuid.go deleted file mode 100644 index 707a069..0000000 --- a/vendor/github.com/intel-go/cpuid/cpuid.go +++ /dev/null @@ -1,1122 +0,0 @@ -// Copyright 2015 Intel Corporation. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package cpuid provides access to inforamtion available with -// CPUID instruction -// All information is gathered during package initialization phase -// so package's public interface doesn't call CPUID intstruction - -package cpuid - -// VendorIndentificationString like "GenuineIntel" or "AuthenticAMD" -var VendorIdentificatorString string - -// ProcessorBrandString like "Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz" -var ProcessorBrandString string - -// SteppingId is Processor Stepping ID as described in -// Intel® 64 and IA-32 Architectures Software Developer’s Manual -var SteppingId uint32 - -// ProcessorType obtained from processor Version Information, according to -// Intel® 64 and IA-32 Architectures Software Developer’s Manual -var ProcessorType uint32 - -// DisplayFamily is Family of processors obtained from processor Version Information, according to -// Intel® 64 and IA-32 Architectures Software Developer’s Manual -var DisplayFamily uint32 - -// Display Model is Model of processor obtained from processor Version Information, according to -// Intel® 64 and IA-32 Architectures Software Developer’s Manual -var DisplayModel uint32 - -// Cache line size in bytes -var CacheLineSize uint32 - -// Maximum number of addressable IDs for logical processors in this physical package -var MaxLogocalCPUId uint32 - -// Initial APIC ID -var InitialAPICId uint32 - -// Cache descriptor's array -// You can iterate like there: -// for _, cacheDescription := range cpuid.CacheDescriptors { -// fmt.Printf("CacheDescriptor: %v\n", cacheDescription) -// } -// See CacheDescriptor type for more information -var CacheDescriptors []CacheDescriptor - -// Smallest monitor-line size in bytes (default is processor's monitor granularity) -var MonLineSizeMin uint32 - -// Largest monitor-line size in bytes (default is processor's monitor granularity) -var MonLineSizeMax uint32 - -// Enumeration of Monitor-Mwait extensions availability status -var MonitorEMX bool - -// Supports treating interrupts as break-event for MWAIT flag -var MonitorIBE bool - -// EnabledAVX flag allows to check if feature AVX is enabled by OS/BIOS -var EnabledAVX bool = false - -// EnabledAVX512 flag allows to check if features AVX512xxx are enabled by OS/BIOS -var EnabledAVX512 bool = false - -type CacheDescriptor struct { - Level int // Cache level - CacheType int // Cache type - CacheName string // Name - CacheSize int // in KBytes (of page size for TLB) - Ways int // Associativity, 0 undefined, 0xFF fully associate - LineSize int // Cache line size in bytes - Entries int // number of entries for TLB - Partioning int // partitioning -} - -// ThermalSensorInterruptThresholds is the number of interrupt thresholds in digital thermal sensor. -var ThermalSensorInterruptThresholds uint32 - -// HasFeature to check if features from FeatureNames map are available on the current processor -func HasFeature(feature uint64) bool { - return (featureFlags & feature) != 0 -} - -// HasExtendedFeature to check if features from ExtendedFeatureNames map are available on the current processor -func HasExtendedFeature(feature uint64) bool { - return (extendedFeatureFlags & feature) != 0 -} - -// HasExtraFeature to check if features from ExtraFeatureNames map are available on the current processor -func HasExtraFeature(feature uint64) bool { - return (extraFeatureFlags & feature) != 0 -} - -// HasThermalAndPowerFeature to check if features from ThermalAndPowerFeatureNames map are available on the current processor -func HasThermalAndPowerFeature(feature uint32) bool { - return (thermalAndPowerFeatureFlags & feature) != 0 -} - -var FeatureNames = map[uint64]string{ - SSE3: "SSE3", - PCLMULQDQ: "PCLMULQDQ", - DTES64: "DTES64", - MONITOR: "MONITOR", - DSI_CPL: "DSI_CPL", - VMX: "VMX", - SMX: "SMX", - EST: "EST", - TM2: "TM2", - SSSE3: "SSSE3", - CNXT_ID: "CNXT_ID", - SDBG: "SDBG", - FMA: "FMA", - CX16: "CX16", - XTPR: "XTPR", - PDCM: "PDCM", - PCID: "PCID", - DCA: "DCA", - SSE4_1: "SSE4_1", - SSE4_2: "SSE4_2", - X2APIC: "X2APIC", - MOVBE: "MOVBE", - POPCNT: "POPCNT", - TSC_DEADLINE: "TSC_DEADLINE", - AES: "AES", - XSAVE: "XSAVE", - OSXSAVE: "OSXSAVE", - AVX: "AVX", - F16C: "F16C", - RDRND: "RDRND", - HYPERVISOR: "HYPERVISOR", - FPU: "FPU", - VME: "VME", - DE: "DE", - PSE: "PSE", - TSC: "TSC", - MSR: "MSR", - PAE: "PAE", - MCE: "MCE", - CX8: "CX8", - APIC: "APIC", - SEP: "SEP", - MTRR: "MTRR", - PGE: "PGE", - MCA: "MCA", - CMOV: "CMOV", - PAT: "PAT", - PSE_36: "PSE_36", - PSN: "PSN", - CLFSH: "CLFSH", - DS: "DS", - ACPI: "ACPI", - MMX: "MMX", - FXSR: "FXSR", - SSE: "SSE", - SSE2: "SSE2", - SS: "SS", - HTT: "HTT", - TM: "TM", - IA64: "IA64", - PBE: "PBE", -} - -var ThermalAndPowerFeatureNames = map[uint32]string{ // From leaf06 - ARAT: "ARAT", - PLN: "PLN", - ECMD: "ECMD", - PTM: "PTM", - HDC: "HDC", - HCFC: "HCFC", - HWP: "HWP", - HWP_NOTIF: "HWP_NOTIF", - HWP_ACTIVITY_WINDOW: "HWP_ACTIVITY_WINDOW", - HWP_ENERGY_PERFORMANCE: "HWP_ENERGY_PERFORMANCE", - HWP_PACKAGE_LEVEL_REQUEST: "HWP_PACKAGE_LEVEL_REQUEST", - PERFORMANCE_ENERGY_BIAS: "PERFORMANCE_ENERGY_BIAS", - TEMPERATURE_SENSOR: "TEMPERATURE_SENSOR", - TURBO_BOOST: "TURBO_BOOST", - TURBO_BOOST_MAX: "TURBO_BOOST_MAX", -} - -var ExtendedFeatureNames = map[uint64]string{ // From leaf07 - FSGSBASE: "FSGSBASE", - IA32_TSC_ADJUST: "IA32_TSC_ADJUST", - BMI1: "BMI1", - HLE: "HLE", - AVX2: "AVX2", - SMEP: "SMEP", - BMI2: "BMI2", - ERMS: "ERMS", - INVPCID: "INVPCID", - RTM: "RTM", - PQM: "PQM", - DFPUCDS: "DFPUCDS", - MPX: "MPX", - PQE: "PQE", - AVX512F: "AVX512F", - AVX512DQ: "AVX512DQ", - RDSEED: "RDSEED", - ADX: "ADX", - SMAP: "SMAP", - AVX512IFMA: "AVX512IFMA", - PCOMMIT: "PCOMMIT", - CLFLUSHOPT: "CLFLUSHOPT", - CLWB: "CLWB", - INTEL_PROCESSOR_TRACE: "INTEL_PROCESSOR_TRACE", - AVX512PF: "AVX512PF", - AVX512ER: "AVX512ER", - AVX512CD: "AVX512CD", - SHA: "SHA", - AVX512BW: "AVX512BW", - AVX512VL: "AVX512VL", - PREFETCHWT1: "PREFETCHWT1", - AVX512VBMI: "AVX512VBMI", -} - -var ExtraFeatureNames = map[uint64]string{ // From leaf 8000 0001 - LAHF_LM: "LAHF_LM", - CMP_LEGACY: "CMP_LEGACY", - SVM: "SVM", - EXTAPIC: "EXTAPIC", - CR8_LEGACY: "CR8_LEGACY", - ABM: "ABM", - SSE4A: "SSE4A", - MISALIGNSSE: "MISALIGNSSE", - PREFETCHW: "PREFETCHW", - OSVW: "OSVW", - IBS: "IBS", - XOP: "XOP", - SKINIT: "SKINIT", - WDT: "WDT", - LWP: "LWP", - FMA4: "FMA4", - TCE: "TCE", - NODEID_MSR: "NODEID_MSR", - TBM: "TBM", - TOPOEXT: "TOPOEXT", - PERFCTR_CORE: "PERFCTR_CORE", - PERFCTR_NB: "PERFCTR_NB", - SPM: "SPM", - DBX: "DBX", - PERFTSC: "PERFTSC", - PCX_L2I: "PCX_L2I", - FPU_2: "FPU", - VME_2: "VME", - DE_2: "DE", - PSE_2: "PSE", - TSC_2: "TSC", - MSR_2: "MSR", - PAE_2: "PAE", - MCE_2: "MCE", - CX8_2: "CX8", - APIC_2: "APIC", - SYSCALL: "SYSCALL", - MTRR_2: "MTRR", - PGE_2: "PGE", - MCA_2: "MCA", - CMOV_2: "CMOV", - PAT_2: "PAT", - PSE36: "PSE36", - MP: "MP", - NX: "NX", - MMXEXT: "MMXEXT", - MMX_2: "MMX", - FXSR_2: "FXSR", - FXSR_OPT: "FXSR_OPT", - PDPE1GB: "PDPE1GB", - RDTSCP: "RDTSCP", - LM: "LM", - _3DNOWEXT: "3DNOWEXT", - _3DNOW: "3DNOW", -} - -var brandStrings = map[string]int{ - "AMDisbetter!": AMD, - "AuthenticAMD": AMD, - "CentaurHauls": CENTAUR, - "CyrixInstead": CYRIX, - "GenuineIntel": INTEL, - "TransmetaCPU": TRANSMETA, - "GenuineTMx86": TRANSMETA, - "Geode by NSC": NATIONALSEMICONDUCTOR, - "NexGenDriven": NEXGEN, - "RiseRiseRise": RISE, - "SiS SiS SiS ": SIS, - "UMC UMC UMC ": UMC, - "VIA VIA VIA ": VIA, - "Vortex86 SoC": VORTEX, - "KVMKVMKVM": KVM, - "Microsoft Hv": HYPERV, - "VMwareVMware": VMWARE, - "XenVMMXenVMM": XEN, -} - -var maxInputValue uint32 -var maxExtendedInputValue uint32 -var extendedModelId uint32 -var extendedFamilyId uint32 -var brandIndex uint32 -var brandId int -var featureFlags uint64 -var thermalAndPowerFeatureFlags uint32 -var extendedFeatureFlags uint64 -var extraFeatureFlags uint64 - -func cpuid_low(arg1, arg2 uint32) (eax, ebx, ecx, edx uint32) // implemented in cpuidlow_amd64.s -func xgetbv_low(arg1 uint32) (eax, edx uint32) // implemented in cpuidlow_amd64.s -func init() { - detectFeatures() -} - -const ( - UKNOWN = iota - AMD - CENTAUR - CYRIX - INTEL - TRANSMETA - NATIONALSEMICONDUCTOR - NEXGEN - RISE - SIS - UMC - VIA - VORTEX - KVM - HYPERV - VMWARE - XEN -) - -func detectFeatures() { - leaf0() - leaf1() - leaf2() - leaf3() - leaf4() - leaf5() - leaf6() - leaf7() - leaf0x80000000() - leaf0x80000001() - leaf0x80000004() - leaf0x80000005() - leaf0x80000006() - - if HasFeature(OSXSAVE) { - eax, _ := xgetbv_low(0) - if (eax & 0x6) == 0x6 { - EnabledAVX = true - } - if (eax & 0xE0) == 0xE0 { - EnabledAVX512 = true - } - } -} - -const ( - SSE3 = uint64(1) << iota - PCLMULQDQ - DTES64 - MONITOR - DSI_CPL - VMX - SMX - EST - TM2 - SSSE3 - CNXT_ID - SDBG - FMA - CX16 - XTPR - PDCM - _ - PCID - DCA - SSE4_1 - SSE4_2 - X2APIC - MOVBE - POPCNT - TSC_DEADLINE - AES - XSAVE - OSXSAVE - AVX - F16C - RDRND - HYPERVISOR - FPU - VME - DE - PSE - TSC - MSR - PAE - MCE - CX8 - APIC - _ - SEP - MTRR - PGE - MCA - CMOV - PAT - PSE_36 - PSN - CLFSH - _ - DS - ACPI - MMX - FXSR - SSE - SSE2 - SS - HTT - TM - IA64 - PBE -) - -const ( - FSGSBASE = uint64(1) << iota - IA32_TSC_ADJUST - _ - BMI1 - HLE - AVX2 - _ - SMEP - BMI2 - ERMS - INVPCID - RTM - PQM - DFPUCDS - MPX - PQE - AVX512F - AVX512DQ - RDSEED - ADX - SMAP - AVX512IFMA - PCOMMIT - CLFLUSHOPT - CLWB - INTEL_PROCESSOR_TRACE - AVX512PF - AVX512ER - AVX512CD - SHA - AVX512BW - AVX512VL - // ECX's const from there - PREFETCHWT1 - AVX512VBMI -) - -const ( - LAHF_LM = uint64(1) << iota - CMP_LEGACY - SVM - EXTAPIC - CR8_LEGACY - ABM - SSE4A - MISALIGNSSE - PREFETCHW - OSVW - IBS - XOP - SKINIT - WDT - _ - LWP - FMA4 - TCE - _ - NODEID_MSR - _ - TBM - TOPOEXT - PERFCTR_CORE - PERFCTR_NB - SPM - DBX - PERFTSC - PCX_L2I - _ - _ - _ - // EDX features from there - FPU_2 - VME_2 - DE_2 - PSE_2 - TSC_2 - MSR_2 - PAE_2 - MCE_2 - CX8_2 - APIC_2 - _ - SYSCALL - MTRR_2 - PGE_2 - MCA_2 - CMOV_2 - PAT_2 - PSE36 - _ - MP - NX - _ - MMXEXT - MMX_2 - FXSR_2 - FXSR_OPT - PDPE1GB - RDTSCP - _ - LM - _3DNOWEXT - _3DNOW -) - -// Thermal and Power Management features -const ( - // EAX bits 0-15 - TEMPERATURE_SENSOR = uint32(1) << iota // Digital temperature sensor - TURBO_BOOST // Intel Turbo Boost Technology available - ARAT // APIC-Timer-always-running feature is supported if set. - _ // Reserved - PLN // Power limit notification controls - ECMD // Clock modulation duty cycle extension - PTM // Package thermal management - HWP // HWP base registers (IA32_PM_ENABLE[bit 0], IA32_HWP_CAPABILITIES, IA32_HWP_REQUEST, IA32_HWP_STATUS) - HWP_NOTIF // IA32_HWP_INTERRUPT MSR - HWP_ACTIVITY_WINDOW // IA32_HWP_REQUEST[bits 41:32] - HWP_ENERGY_PERFORMANCE // IA32_HWP_REQUEST[bits 31:24] - HWP_PACKAGE_LEVEL_REQUEST // IA32_HWP_REQUEST_PKG MSR - _ // Reserved (eax bit 12) - HDC // HDC base registers IA32_PKG_HDC_CTL, IA32_PM_CTL1, IA32_THREAD_STALL MSRs - TURBO_BOOST_MAX // Intel® Turbo Boost Max Technology - _ // Reserved (eax bit 15) - - // ECX bits 0-15 - HCFC // Hardware Coordination Feedback Capability - _ - _ - PERFORMANCE_ENERGY_BIAS // Processor supports performance-energy bias preference -) - -const ( - NULL = iota - DATA_CACHE - INSTRUCTION_CACHE - UNIFIED_CACHE - TLB - DTLB - STLB - PREFETCH -) - -var leaf02Names = [...]string{ - "NULL", - "DATA_CACHE", - "INSTRUCTION_CACHE", - "UNIFIED_CACHE", - "TLB", - "DTLB", - "STLB", - "PREFETCH", -} - -func leaf0() { - - eax, ebx, ecx, edx := cpuid_low(0, 0) - - maxInputValue = eax - - VendorIdentificatorString = string(int32sToBytes(ebx, edx, ecx)) - brandId = brandStrings[VendorIdentificatorString] -} - -func leaf1() { - - if maxInputValue < 1 { - return - } - - eax, ebx, ecx, edx := cpuid_low(1, 0) - // Parse EAX - SteppingId = (eax & 0xF) - modelId := (eax >> 4) & 0xF - familyId := (eax >> 8) & 0xF - ProcessorType = (eax >> 12) & 0x3 - ExtendedModelId := (eax >> 16) & 0xF - extendedFamilyId := (eax >> 20) & 0xFF - - DisplayFamily = familyId - DisplayModel = modelId - - if familyId == 0xF { - DisplayFamily = extendedFamilyId + familyId - } - - if familyId == 0x6 || familyId == 0xF { - DisplayModel = ExtendedModelId<<4 + modelId - } - - // Parse EBX - brandIndex = ebx & 0xFF - CacheLineSize = ((ebx >> 8) & 0xFF) << 3 - MaxLogocalCPUId = (ebx >> 16) & 0xFF - InitialAPICId = (ebx >> 24) - - // Parse ECX & EDX not needed. Ask through HasFeature function - featureFlags = (uint64(edx) << 32) | uint64(ecx) -} - -func leaf2() { - - if brandId != INTEL { - return - } - if maxInputValue < 2 { - return - } - - bytes := int32sToBytes(cpuid_low(2, 0)) - - for i := 0; i < len(bytes); i++ { - if (i%4 == 0) && (bytes[i+3]&(1<<7) != 0) { - i += 4 - continue - } - if bytes[i] == 0xFF { // it means that we should use leaf 4 for cache info - CacheDescriptors = CacheDescriptors[0:0] - break - } - CacheDescriptors = append(CacheDescriptors, leaf02Descriptors[int16(bytes[i])]) - } -} - -func leaf3() { - if brandId != INTEL { - return - } - - if maxInputValue < 3 { - return - } - // TODO SerialNumber for < Pentium 4 -} - -func leaf4() { - - if brandId != INTEL { - return - } - - if maxInputValue < 4 { - return - } - - cacheId := 0 - for { - eax, ebx, ecx, _ := cpuid_low(4, uint32(cacheId)) - cacheId++ - cacheType := eax & 0xF - - if cacheType == NULL { - break - } - - cacheLevel := (eax >> 5) & 0x7 - // selfInitializingCacheLevel := eax & (1<<8) - // fullyAssociativeCache := eax & (1<<9) - // maxNumLogicalCoresSharing := (eax >> 14) & 0x3FF - // maxNumPhisCores := (eax >> 26) & 0x3F - systemCoherencyLineSize := (ebx & 0xFFF) + 1 - physicalLinePartions := (ebx>>12)&0x3FF + 1 - waysOfAssiociativity := (ebx>>22)&0x3FF + 1 - numberOfSets := ecx + 1 - // writeBackInvalidate := edx & 1 - // cacheInclusiveness := edx & (1<<1) - // complexCacheIndexing := edx & (1<<2) - cacheSize := (waysOfAssiociativity * physicalLinePartions * - systemCoherencyLineSize * numberOfSets) >> 10 - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{int(cacheLevel), - int(cacheType), - "", - int(cacheSize), - int(waysOfAssiociativity), - int(systemCoherencyLineSize), - int(numberOfSets), - int(physicalLinePartions), - }) - } -} - -func leaf5() { - if maxInputValue < 5 { - return - } - - eax, ebx, ecx, _ := cpuid_low(4, 0) // TODO process EDX with C0-C7 C-states - MonLineSizeMax = eax & (0xFFFF) - MonLineSizeMax = ebx & (0xFFFF) - MonitorEMX = (ecx & (1 << 0)) != 0 - MonitorIBE = (ecx & (1 << 1)) != 0 - -} - -func leaf6() { - // Thermal and Power Management Features for Intel - if maxInputValue < 6 { - return - } - - eax, ebx, ecx, _ := cpuid_low(6, 0) - thermalAndPowerFeatureFlags = (eax & 0xFFFF) | (ecx << 16) - ThermalSensorInterruptThresholds = ebx & 7 -} - -func leaf7() { - _, ebx, ecx, _ := cpuid_low(7, 0) - extendedFeatureFlags = (uint64(ecx) << 32) | uint64(ebx) -} - -func leaf0x80000000() { - maxExtendedInputValue, _, _, _ = cpuid_low(0x80000000, 0) -} - -func leaf0x80000001() { - if maxExtendedInputValue < 0x80000001 { - return - } - _, _, ecx, edx := cpuid_low(0x80000001, 0) - //extendedProcessorSignatureAndFeatureBits := eax - extraFeatureFlags = (uint64(edx) << 32) | uint64(ecx) -} - -// leaf0x80000004 looks at the Processor Brand String in leaves 0x80000002 through 0x80000004 -func leaf0x80000004() { - if maxExtendedInputValue < 0x80000004 { - return - } - - ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000002, 0))) - ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000003, 0))) - ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000004, 0))) -} - -func leaf0x80000005() { - // AMD L1 Cache and TLB Information - if maxExtendedInputValue < 0x80000005 { - return - } - - if brandId != AMD { - return - } - - eax, ebx, ecx, edx := cpuid_low(0x80000005, 0) - - L1DTlb2and4MAssoc := (eax >> 24) & 0xFF - L1DTlb2and4MSize := (eax >> 16) & 0xFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{1, - DTLB, - "DTLB 2M/4M", - 2 * 1024, - int(L1DTlb2and4MAssoc), - -1, - int(L1DTlb2and4MSize), - 0, - }) - - L1ITlb2and4MAssoc := (eax >> 8) & 0xFF - L1ITlb2and4MSize := (eax) & 0xFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{1, - TLB, - "ITLB 2M/4M", - 2 * 1024, - int(L1ITlb2and4MAssoc), - -1, - int(L1ITlb2and4MSize), - 0, - }) - - L1DTlb4KAssoc := (ebx >> 24) & 0xFF - L1DTlb4KSize := (ebx >> 16) & 0xFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{1, - DTLB, - "DTLB 4K", - 4, - int(L1DTlb4KAssoc), - -1, - int(L1DTlb4KSize), - 0, - }) - - L1ITlb4KAssoc := (ebx >> 8) & 0xFF - L1ITlb4KSize := (ebx) & 0xFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{1, - TLB, - "ITLB 4K", - 4, - int(L1ITlb4KAssoc), - -1, - int(L1ITlb4KSize), - 0, - }) - - L1DcSize := (ecx >> 24) & 0xFF - L1DcAssoc := (ecx >> 16) & 0xFF - L1DcLinesPerTag := (ecx >> 8) & 0xFF - L1DcLineSize := (ecx >> 0) & 0xFF - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{1, - DATA_CACHE, - "L1 Data cache", - int(L1DcSize), - int(L1DcAssoc), - int(L1DcLineSize), - -1, - int(L1DcLinesPerTag), - }) - - L1IcSize := (edx >> 24) & 0xFF - L1IcAssoc := (edx >> 16) & 0xFF - L1IcLinesPerTag := (edx >> 8) & 0xFF - L1IcLineSize := (edx >> 0) & 0xFF - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{1, - INSTRUCTION_CACHE, - "L1 Instruction cache", - int(L1IcSize), - int(L1IcAssoc), - int(L1IcLineSize), - -1, - int(L1IcLinesPerTag), - }) -} - -func leaf0x80000006() { - - if maxExtendedInputValue < 0x80000006 { - return - } - - var associativityEncodings = map[uint]uint{ - 0x00: 0, - 0x01: 1, - 0x02: 2, - 0x04: 4, - 0x06: 8, - 0x08: 16, - 0x0A: 32, - 0x0B: 48, - 0x0C: 64, - 0x0D: 96, - 0x0E: 128, - 0x0F: 0xFF, // - Fully associative - } - - eax, ebx, ecx, edx := cpuid_low(0x80000006, 0) - - if brandId == INTEL { - - CacheLineSize := (ecx >> 0) & 0xFF - L2Associativity := uint((ecx >> 12) & 0xF) - CacheSize := (ecx >> 16) & 0xFFFF - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{2, - 0, - "Cache info from leaf 0x80000006 for Intel", - int(CacheSize), - int(associativityEncodings[L2Associativity]), - int(CacheLineSize), - -1, - 0, - }) - } - - if brandId == AMD { - - L2DTlb2and4MAssoc := uint((eax >> 28) & 0xF) - L2DTlb2and4MSize := (eax >> 16) & 0xFFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{2, - DTLB, - "DTLB 2M/4M", - 2 * 1024, - int(associativityEncodings[L2DTlb2and4MAssoc]), - -1, - int(L2DTlb2and4MSize), - 0, - }) - - L2ITlb2and4MAssoc := uint((eax >> 12) & 0xF) - L2ITlb2and4MSize := (eax) & 0xFFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{2, - TLB, - "ITLB 2M/4M", - 2 * 1024, - int(associativityEncodings[L2ITlb2and4MAssoc]), - -1, - int(L2ITlb2and4MSize), - 0, - }) - - L2DTlb4KAssoc := uint((ebx >> 28) & 0xF) - L2DTlb4KSize := (ebx >> 16) & 0xFFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{2, - DTLB, - "DTLB 4K", - 4, - int(associativityEncodings[L2DTlb4KAssoc]), - -1, - int(L2DTlb4KSize), - 0, - }) - - L2ITlb4KAssoc := uint((ebx >> 12) & 0xF) - L2ITlb4KSize := (ebx) & 0xFFF - - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{2, - TLB, - "ITLB 4K", - 4, - int(associativityEncodings[L2ITlb4KAssoc]), - -1, - int(L2ITlb4KSize), - 0, - }) - - L2Size := (ecx >> 16) & 0xFFFF - L2Assoc := uint((ecx >> 12) & 0xF) - L2LinesPerTag := (ecx >> 8) & 0xF - L2LineSize := (ecx >> 0) & 0xFF - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{2, - DATA_CACHE, - "L2 Data cache", - int(L2Size), - int(associativityEncodings[L2Assoc]), - int(L2LineSize), - -1, - int(L2LinesPerTag), - }) - - L3Size := ((edx >> 18) & 0xF) * 512 - L3Assoc := uint((edx >> 12) & 0xF) - L3LinesPerTag := (edx >> 8) & 0xF - L3LineSize := (edx >> 0) & 0xFF - CacheDescriptors = append(CacheDescriptors, - CacheDescriptor{3, - DATA_CACHE, - "L3 Data cache", - int(L3Size), - int(associativityEncodings[L3Assoc]), - int(L3LineSize), - -1, - int(L3LinesPerTag), - }) - } -} - -// TODO split fused descritops with bits in high key's byte like for 0x49 -var leaf02Descriptors = map[int16]CacheDescriptor{ - 0x01: {-1, TLB, "Instruction TLB", 4, 4, -1, 32, 0}, - 0x02: {-1, TLB, "Instruction TLB", 4 * 1024, 0xFF, -1, 2, 0}, - 0x03: {-1, TLB, "Data TLB", 4, 4, -1, 64, 0}, - 0x04: {-1, TLB, "Data TLB", 4 * 1024, 4, -1, 8, 0}, - 0x05: {-1, TLB, "Data TLB1", 4 * 1024, 4, -1, 32, 0}, - 0x06: {1, INSTRUCTION_CACHE, "1st-level instruction cache", 8, 4, 32, -1, 0}, - 0x08: {1, INSTRUCTION_CACHE, "1st-level instruction cache", 16, 4, 32, -1, 0}, - 0x09: {1, INSTRUCTION_CACHE, "1st-level instruction cache", 32, 4, 64, -1, 0}, - 0x0A: {1, DATA_CACHE, "1st-level data cache", 8, 2, 32, -1, 0}, - 0x0B: {-1, TLB, "Instruction TLB", 4 * 1024, 4, -1, 4, 0}, - 0x0C: {1, DATA_CACHE, "1st-level data cache", 16, 4, 32, -1, 0}, - 0x0D: {1, DATA_CACHE, "1st-level data cache", 16, 4, 64, -1, 0}, - 0x0E: {1, DATA_CACHE, "1st-level data cache", 24, 6, 64, -1, 0}, - 0x1D: {2, DATA_CACHE, "2nd-level cache", 128, 2, 64, -1, 0}, - 0x21: {2, DATA_CACHE, "2nd-level cache", 256, 8, 64, -1, 0}, - 0x22: {3, DATA_CACHE, "3nd-level cache", 512, 4, 64, -1, 2}, - 0x23: {3, DATA_CACHE, "3nd-level cache", 1 * 1024, 8, 64, -1, 2}, - 0x24: {2, DATA_CACHE, "2nd-level cache", 1 * 1024, 16, 64, -1, 0}, - 0x25: {3, DATA_CACHE, "3nd-level cache", 2 * 1024, 8, 64, -1, 2}, - 0x29: {3, DATA_CACHE, "2nd-level cache", 4 * 1024, 8, 64, -1, 2}, - 0x2C: {1, DATA_CACHE, "1st-level cache", 32, 8, 64, -1, 0}, - 0x30: {1, INSTRUCTION_CACHE, "1st-level instruction cache", 32, 8, 64, -1, 0}, - 0x40: {-1, DATA_CACHE, "No 2nd-level cache or, if processor contains a " + - "valid 2nd-level cache, no 3rd-level cache", -1, -1, -1, -1, 0}, - 0x41: {2, DATA_CACHE, "2nd-level cache", 128, 4, 32, -1, 0}, - 0x42: {2, DATA_CACHE, "2nd-level cache", 256, 4, 32, -1, 0}, - 0x43: {2, DATA_CACHE, "2nd-level cache", 512, 4, 32, -1, 0}, - 0x44: {2, DATA_CACHE, "2nd-level cache", 1 * 1024, 4, 32, -1, 0}, - 0x45: {2, DATA_CACHE, "2nd-level cache", 2 * 1024, 4, 32, -1, 0}, - 0x46: {3, DATA_CACHE, "3nd-level cache", 4 * 1024, 4, 64, -1, 0}, - 0x47: {3, DATA_CACHE, "3nd-level cache", 8 * 1024, 8, 64, -1, 0}, - 0x48: {2, DATA_CACHE, "2nd-level cache", 3 * 1024, 12, 64, -1, 0}, - 0x49: {2, DATA_CACHE, "2nd-level cache", 4 * 1024, 16, 64, -1, 0}, - // (Intel Xeon processor MP, Family 0FH, Model 06H) - (0x49 | (1 << 8)): {3, DATA_CACHE, "3nd-level cache", 4 * 1024, 16, 64, -1, 0}, - 0x4A: {3, DATA_CACHE, "3nd-level cache", 6 * 1024, 12, 64, -1, 0}, - 0x4B: {3, DATA_CACHE, "3nd-level cache", 8 * 1024, 16, 64, -1, 0}, - 0x4C: {3, DATA_CACHE, "3nd-level cache", 12 * 1024, 12, 64, -1, 0}, - 0x4D: {3, DATA_CACHE, "3nd-level cache", 16 * 1024, 16, 64, -1, 0}, - 0x4E: {2, DATA_CACHE, "3nd-level cache", 6 * 1024, 24, 64, -1, 0}, - 0x4F: {-1, TLB, "Instruction TLB", 4, -1, -1, 32, 0}, - 0x50: {-1, TLB, "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages", 4, -1, -1, 64, 0}, - 0x51: {-1, TLB, "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages", 4, -1, -1, 128, 0}, - 0x52: {-1, TLB, "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages", 4, -1, -1, 256, 0}, - 0x55: {-1, TLB, "Instruction TLB: 2-MByte or 4-MByte pages", 2 * 1024, 0xFF, -1, 7, 0}, - 0x56: {-1, TLB, "Data TLB0", 4 * 1024, 4, -1, 16, 0}, - 0x57: {-1, TLB, "Data TLB0", 4, 4, -1, 16, 0}, - 0x59: {-1, TLB, "Data TLB0", 4, 0xFF, -1, 16, 0}, - 0x5A: {-1, TLB, "Data TLB0 2-MByte or 4 MByte pages", 2 * 1024, 4, -1, 32, 0}, - 0x5B: {-1, TLB, "Data TLB 4 KByte and 4 MByte pages", 4, -1, -1, 64, 0}, - 0x5C: {-1, TLB, "Data TLB 4 KByte and 4 MByte pages", 4, -1, -1, 128, 0}, - 0x5D: {-1, TLB, "Data TLB 4 KByte and 4 MByte pages", 4, -1, -1, 256, 0}, - 0x60: {1, DATA_CACHE, "1st-level data cache", 16, 8, 64, -1, 0}, - 0x61: {-1, TLB, "Instruction TLB", 4, 0xFF, -1, 48, 0}, - 0x63: {-1, TLB, "Data TLB", 1 * 1024 * 1024, 4, -1, 4, 0}, - 0x66: {1, DATA_CACHE, "1st-level data cache", 8, 4, 64, -1, 0}, - 0x67: {1, DATA_CACHE, "1st-level data cache", 16, 4, 64, -1, 0}, - 0x68: {1, DATA_CACHE, "1st-level data cache", 32, 4, 64, -1, 0}, - 0x70: {1, INSTRUCTION_CACHE, "Trace cache (size in K of uop)", 12, 8, -1, -1, 0}, - 0x71: {1, INSTRUCTION_CACHE, "Trace cache (size in K of uop)", 16, 8, -1, -1, 0}, - 0x72: {1, INSTRUCTION_CACHE, "Trace cache (size in K of uop)", 32, 8, -1, -1, 0}, - 0x76: {-1, TLB, "Instruction TLB: 2M/4M pages", 2 * 1024, 0xFF, -1, 8, 0}, - 0x78: {2, DATA_CACHE, "2nd-level cache", 1 * 1024, 4, 64, -1, 0}, - 0x79: {2, DATA_CACHE, "2nd-level cache", 128, 8, 64, -1, 2}, - 0x7A: {2, DATA_CACHE, "2nd-level cache", 256, 8, 64, -1, 2}, - 0x7B: {2, DATA_CACHE, "2nd-level cache", 512, 8, 64, -1, 2}, - 0x7C: {2, DATA_CACHE, "2nd-level cache", 1 * 1024, 8, 64, -1, 2}, - 0x7D: {2, DATA_CACHE, "2nd-level cache", 2 * 1024, 8, 64, -1, 0}, - 0x7F: {2, DATA_CACHE, "2nd-level cache", 512, 2, 64, -1, 0}, - 0x80: {2, DATA_CACHE, "2nd-level cache", 512, 8, 64, -1, 0}, - 0x82: {2, DATA_CACHE, "2nd-level cache", 256, 8, 32, -1, 0}, - 0x83: {2, DATA_CACHE, "2nd-level cache", 512, 8, 32, -1, 0}, - 0x84: {2, DATA_CACHE, "2nd-level cache", 1 * 1024, 8, 32, -1, 0}, - 0x85: {2, DATA_CACHE, "2nd-level cache", 2 * 1024, 8, 32, -1, 0}, - 0x86: {2, DATA_CACHE, "2nd-level cache", 512, 4, 32, -1, 0}, - 0x87: {2, DATA_CACHE, "2nd-level cache", 1 * 1024, 8, 64, -1, 0}, - 0xA0: {-1, DTLB, "DTLB", 4, 0xFF, -1, 32, 0}, - 0xB0: {-1, TLB, "Instruction TLB", 4, 4, -1, 128, 0}, - 0xB1: {-1, TLB, "Instruction TLB 2M pages 4 way 8 entries or" + - "4M pages 4-way, 4 entries", 2 * 1024, 4, -1, 8, 0}, - 0xB2: {-1, TLB, "Instruction TLB", 4, 4, -1, 64, 0}, - 0xB3: {-1, TLB, "Data TLB", 4, 4, -1, 128, 0}, - 0xB4: {-1, TLB, "Data TLB1", 4, 4, -1, 256, 0}, - 0xB5: {-1, TLB, "Instruction TLB", 4, 8, -1, 64, 0}, - 0xB6: {-1, TLB, "Instruction TLB", 4, 8, -1, 128, 0}, - 0xBA: {-1, TLB, "Data TLB1", 4, 4, -1, 64, 0}, - 0xC0: {-1, TLB, "Data TLB: 4 KByte and 4 MByte pages", 4, 4, -1, 8, 0}, - 0xC1: {-1, STLB, "Shared 2nd-Level TLB: 4Kbyte and 2Mbyte pages", 4, 8, -1, 1024, 0}, - 0xC2: {-1, DTLB, "DTLB 4KByte/2 MByte pages", 4, 4, -1, 16, 0}, - 0xC3: {-1, STLB, "Shared 2nd-Level TLB: " + - "4 KByte /2 MByte pages, 6-way associative, 1536 entries." + - "Also 1GBbyte pages, 4-way,16 entries.", 4, 6, -1, 1536, 0}, - 0xCA: {-1, STLB, "Shared 2nd-Level TLB", 4, 4, -1, 512, 0}, - 0xD0: {3, DATA_CACHE, "3nd-level cache", 512, 4, 64, -1, 0}, - 0xD1: {3, DATA_CACHE, "3nd-level cache", 1 * 1024, 4, 64, -1, 0}, - 0xD2: {3, DATA_CACHE, "3nd-level cache", 2 * 1024, 4, 64, -1, 0}, - 0xD6: {3, DATA_CACHE, "3nd-level cache", 1 * 1024, 8, 64, -1, 0}, - 0xD7: {3, DATA_CACHE, "3nd-level cache", 2 * 1024, 8, 64, -1, 0}, - 0xD8: {3, DATA_CACHE, "3nd-level cache", 4 * 1024, 8, 64, -1, 0}, - 0xDC: {3, DATA_CACHE, "3nd-level cache", 1 * 1536, 12, 64, -1, 0}, - 0xDD: {3, DATA_CACHE, "3nd-level cache", 3 * 1024, 12, 64, -1, 0}, - 0xDE: {3, DATA_CACHE, "3nd-level cache", 6 * 1024, 12, 64, -1, 0}, - 0xE2: {3, DATA_CACHE, "3nd-level cache", 2 * 1024, 16, 64, -1, 0}, - 0xE3: {3, DATA_CACHE, "3nd-level cache", 4 * 1024, 16, 64, -1, 0}, - 0xE4: {3, DATA_CACHE, "3nd-level cache", 8 * 1024, 16, 64, -1, 0}, - 0xEA: {3, DATA_CACHE, "3nd-level cache", 12 * 1024, 24, 64, -1, 0}, - 0xEB: {3, DATA_CACHE, "3nd-level cache", 18 * 1024, 24, 64, -1, 0}, - 0xEC: {3, DATA_CACHE, "3nd-level cache", 24 * 1024, 24, 64, -1, 0}, - 0xF0: {-1, PREFETCH, "", 64, -1, -1, -1, 0}, - 0xF1: {-1, PREFETCH, "", 128, -1, -1, -1, 0}, - 0xFF: {-1, NULL, "CPUID leaf 2 does not report cache descriptor " + - "information, use CPUID leaf 4 to query cache parameters", - -1, -1, -1, -1, 0}, -} - -func int32sToBytes(args ...uint32) []byte { - var result []byte - - for _, arg := range args { - result = append(result, - byte((arg)&0xFF), - byte((arg>>8)&0xFF), - byte((arg>>16)&0xFF), - byte((arg>>24)&0xFF)) - } - - return result -} diff --git a/vendor/github.com/intel-go/cpuid/cpuidlow_amd64.s b/vendor/github.com/intel-go/cpuid/cpuidlow_amd64.s deleted file mode 100644 index 20da845..0000000 --- a/vendor/github.com/intel-go/cpuid/cpuidlow_amd64.s +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017 Intel Corporation. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -#include "textflag.h" - -// func cpuid_low(arg1, arg2 uint32) (eax, ebx, ecx, edx uint32) -TEXT ·cpuid_low(SB),NOSPLIT,$0-24 - MOVL arg1+0(FP), AX - MOVL arg2+4(FP), CX - CPUID - MOVL AX, eax+8(FP) - MOVL BX, ebx+12(FP) - MOVL CX, ecx+16(FP) - MOVL DX, edx+20(FP) - RET -// func xgetbv_low(arg1 uint32) (eax, edx uint32) - TEXT ·xgetbv_low(SB),NOSPLIT,$0-16 - MOVL arg1+0(FP), CX - BYTE $0x0F - BYTE $0x01 - BYTE $0xD0 - MOVL AX,eax+8(FP) - MOVL DX,edx+12(FP) - RET diff --git a/vendor/github.com/intel-go/cpuid/example/example.go b/vendor/github.com/intel-go/cpuid/example/example.go deleted file mode 100644 index 1f55a44..0000000 --- a/vendor/github.com/intel-go/cpuid/example/example.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2017 Intel Corporation. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "github.com/intel-go/cpuid" -) - -func main() { - fmt.Printf("VendorString: %s\n", cpuid.VendorIdentificatorString) - fmt.Printf("ProcessorBrandString: %s\n", cpuid.ProcessorBrandString) - fmt.Printf("SteppingId: %d\n", cpuid.SteppingId) - fmt.Printf("ProcessorType: %d\n", cpuid.ProcessorType) - fmt.Printf("DisplayFamily: %d\n", cpuid.DisplayFamily) - fmt.Printf("DisplayModel: %d\n", cpuid.DisplayModel) - fmt.Printf("CacheLineSize: %d\n", cpuid.CacheLineSize) - fmt.Printf("MaxLogocalCPUId:%d\n", cpuid.MaxLogocalCPUId) - fmt.Printf("InitialAPICId: %d\n", cpuid.InitialAPICId) - fmt.Printf("Smallest monitor-line size in bytes: %d\n", cpuid.MonLineSizeMin) - fmt.Printf("Largest monitor-line size in bytes: %d\n", cpuid.MonLineSizeMax) - fmt.Printf("Monitor Interrupt break-event is supported: %v\n", cpuid.MonitorIBE) - fmt.Printf("MONITOR/MWAIT extensions are supported: %v\n", cpuid.MonitorEMX) - fmt.Printf("AVX state: %v\n", cpuid.EnabledAVX) - fmt.Printf("AVX-512 state: %v\n", cpuid.EnabledAVX512) - fmt.Printf("Interrupt thresholds in digital thermal sensor: %v\n", cpuid.ThermalSensorInterruptThresholds) - - fmt.Printf("Features: ") - for i := uint64(0); i < 64; i++ { - if cpuid.HasFeature(1 << i) { - fmt.Printf("%s ", cpuid.FeatureNames[1< 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // . followed by 1 or more digits. - if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { - s = s[2:] - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // e or E followed by an optional - or + and - // 1 or more digits. - if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { - s = s[1:] - if s[0] == '+' || s[0] == '-' { - s = s[1:] - if s == "" { - return false - } - } - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // Make sure we are at the end. - return s == "" -} - -// decodeState represents the state while decoding a JSON value. -type decodeState struct { - data []byte - off int // read offset in data - scan scanner - savedError error - useNumber bool -} - -// errPhase is used for errors that should not happen unless -// there is a bug in the JSON decoder or something is editing -// the data slice while the decoder executes. -var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?") - -func (d *decodeState) init(data []byte) *decodeState { - d.data = data - d.off = 0 - d.savedError = nil - return d -} - -// error aborts the decoding by panicking with err. -func (d *decodeState) error(err error) { - panic(err) -} - -// saveError saves the first err it is called with, -// for reporting at the end of the unmarshal. -func (d *decodeState) saveError(err error) { - if d.savedError == nil { - d.savedError = err - } -} - -// next cuts off and returns the next full JSON value -// The next value is known to be an object or array or a literal -func (d *decodeState) next() []byte { - startop, start := d.peekRecord() - - var endop int - - switch startop { - case scanBeginArray: - endop = scanEndArray - case scanBeginObject: - endop = scanEndObject - case scanBeginLiteral: - endop = scanEndLiteral - default: - panic(errPhase) - } - - count := 1 //counts number of open and not closed brackets. - d.skipRecord() - end := 0 //end of value - op := startop - for count != 0 { //we need here cycle because of nested objects and slices - op, end = d.takeRecord() - - if op == startop { - count++ - } - - if op == endop { - count-- - } - - } - return d.data[start : end+1] -} - -//wrappers scanner funcs -func (d *decodeState) takeRecord() (int, int) { - return d.scan.peekState(), d.scan.takePos() -} - -func (d *decodeState) peekRecord() (int, int) { - return d.scan.peekState(), d.scan.peekPos() -} -func (d *decodeState) takeState() int { - return d.scan.takeState() -} - -func (d *decodeState) peekState() int { - return d.scan.peekState() -} - -func (d *decodeState) takePos() int { - return d.scan.takePos() -} - -func (d *decodeState) peekPos() int { - return d.scan.peekPos() -} - -func (d *decodeState) skipRecord() { - d.scan.skipRecord() -} - -// value decodes a JSON value from d.data[d.off:] into the value. -// it updates d.off to point past the decoded value. -func (d *decodeState) value(v reflect.Value) { - if !v.IsValid() { - d.next() - return - } - switch op := d.peekState(); op { - default: - d.error(errPhase) - - case scanBeginArray: - d.array(v) - - case scanBeginObject: - d.object(v) - - case scanBeginLiteral: - d.literal(v) - } -} - -type unquotedValue struct{} - -// valueQuoted is like value but decodes a -// quoted string literal or literal null into an interface value. -// If it finds anything other than a quoted string literal or null, -// valueQuoted returns unquotedValue{}. -func (d *decodeState) valueQuoted() interface{} { - switch op := d.peekState(); op { - default: - d.error(errPhase) - - case scanBeginArray: - d.array(reflect.Value{}) - - case scanBeginObject: - d.object(reflect.Value{}) - - case scanBeginLiteral: - switch v := d.literalInterface().(type) { - case nil, string: - return v - } - } - return unquotedValue{} -} - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func (d *decodeState) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// array consumes an array from d.data[d.off-1:], decoding into the value v. -// the first byte of the array ('[') has been read already. -func (d *decodeState) array(v reflect.Value) { - // Check for unmarshaler. - - u, ut, pv := d.indirect(v, false) - if u != nil { - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.peekPos() + 1)}) - d.next() - return - } - - v = pv - - // Check type of target. - switch v.Kind() { - case reflect.Interface: - if v.NumMethod() == 0 { - // Decoding into nil interface? Switch to non-reflect code. - v.Set(reflect.ValueOf(d.arrayInterface())) - return - } - // Otherwise it's invalid. - fallthrough - default: - d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.peekPos() + 1)}) - d.next() - return - case reflect.Array: - case reflect.Slice: - break - } - d.skipRecord() //skip [ - i := 0 - for { - // Look ahead for ] - can only happen on first iteration. - op := d.peekState() - if op == scanEndArray { - d.skipRecord() - - break - } - if op != scanBeginLiteral && op != scanBeginObject && op != scanBeginArray { - d.error(errPhase) - } - - // Get element of array, growing if necessary. - if v.Kind() == reflect.Slice { - // Grow slice if necessary - if i >= v.Cap() { - newcap := v.Cap() + v.Cap()/2 - if newcap < 4 { - newcap = 4 - } - newv := reflect.MakeSlice(v.Type(), v.Len(), newcap) - reflect.Copy(newv, v) - v.Set(newv) - } - if i >= v.Len() { - v.SetLen(i + 1) - } - } - - if i < v.Len() { - // Decode into element. - d.value(v.Index(i)) - } else { - // Ran out of fixed array: skip. - d.value(reflect.Value{}) - } - i++ - - } - - if i < v.Len() { - if v.Kind() == reflect.Array { - // Array. Zero the rest. - z := reflect.Zero(v.Type().Elem()) - for ; i < v.Len(); i++ { - v.Index(i).Set(z) - } - } else { - v.SetLen(i) - } - } - if i == 0 && v.Kind() == reflect.Slice { - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - } -} - -var nullLiteral = []byte("null") - -// object consumes an object from d.data[d.off-1:], decoding into the value v. -func (d *decodeState) object(v reflect.Value) { - // Check for unmarshaler. - - u, ut, pv := d.indirect(v, false) - if u != nil { - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.peekPos() + 1)}) - d.next() // skip over { } in input - return - } - v = pv - - // Decoding into nil interface? Switch to non-reflect code. - if v.Kind() == reflect.Interface && v.NumMethod() == 0 { - v.Set(reflect.ValueOf(d.objectInterface())) - return - } - - // Check type of target: struct or map[string]T - switch v.Kind() { - case reflect.Map: - // map must have string kind - t := v.Type() - if t.Key().Kind() != reflect.String { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.peekPos() + 1)}) - d.next() // skip over { } in input - return - } - if v.IsNil() { - v.Set(reflect.MakeMap(t)) - } - case reflect.Struct: - - default: - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.peekPos() + 1)}) - d.next() // skip over { } in input - return - } - - var mapElem reflect.Value - - d.skipRecord() // skip BeginObject - - for { - // Read opening " of string key or closing }. - op := d.peekState() - if op == scanEndObject { - // closing } - can only happen on first iteration. - - d.skipRecord() - break - } - if op != scanBeginLiteral { - d.error(errPhase) - } - - // Read key. - start := d.takePos() - op, end := d.takeRecord() - if op != scanEndLiteral { - d.error(errPhase) - } - item := d.data[start : end+1] - key, ok := unquoteBytes(item) - if !ok { - d.error(errPhase) - } - - // Figure out field corresponding to key. - var subv reflect.Value - destring := false // whether the value is wrapped in a string to be decoded first - - if v.Kind() == reflect.Map { - elemType := v.Type().Elem() - if !mapElem.IsValid() { - mapElem = reflect.New(elemType).Elem() - } else { - mapElem.Set(reflect.Zero(elemType)) - } - subv = mapElem - } else { - var f *field - fields := cachedTypeFields(v.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, key) { - f = ff - break - } - if f == nil && ff.equalFold(ff.nameBytes, key) { - f = ff - } - } - if f != nil { - subv = v - destring = f.quoted - for _, i := range f.index { - if subv.Kind() == reflect.Ptr { - if subv.IsNil() { - subv.Set(reflect.New(subv.Type().Elem())) - } - subv = subv.Elem() - } - subv = subv.Field(i) - } - } - } - // Read value. - if destring { - switch qv := d.valueQuoted().(type) { - case nil: - d.literalStore(nullLiteral, subv, false) - case string: - d.literalStore([]byte(qv), subv, true) - default: - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type())) - } - } else { - d.value(subv) - } - - // Write value back to map; - // if using struct, subv points into struct already. - if v.Kind() == reflect.Map { - kv := reflect.ValueOf(key).Convert(v.Type().Key()) - v.SetMapIndex(kv, subv) - } - - } -} - -// literal consumes a literal from d.data[d.off-1:], decoding into the value v. -// The first byte of the literal has been read already -// (that's how the caller knows it's a literal). -func (d *decodeState) literal(v reflect.Value) { - start := d.takePos() - op, end := d.takeRecord() - if op != scanEndLiteral { - d.error(errPhase) - } - d.literalStore(d.data[start:end+1], v, false) -} - -// convertNumber converts the number literal s to a float64 or a Number -// depending on the setting of d.useNumber. -func (d *decodeState) convertNumber(s string) (interface{}, error) { - if d.useNumber { - return Number(s), nil - } - f, err := strconv.ParseFloat(s, 64) - if err != nil { - return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0), int64(d.peekPos() + 1)} - } - return f, nil -} - -var numberType = reflect.TypeOf(Number("")) - -// literalStore decodes a literal stored in item into v. -// -// fromQuoted indicates whether this literal came from unwrapping a -// string from the ",string" struct tag option. this is used only to -// produce more helpful error messages. -func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) { - // Check for unmarshaler. - if len(item) == 0 { - //Empty string given - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - return - } - wantptr := item[0] == 'n' // null - u, ut, pv := d.indirect(v, wantptr) - if u != nil { - err := u.UnmarshalJSON(item) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - if item[0] != '"' { - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.peekPos() + 1)}) - } - return - } - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - err := ut.UnmarshalText(s) - if err != nil { - d.error(err) - } - return - } - - v = pv - - switch c := item[0]; c { - case 'n': // null - switch v.Kind() { - case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: - v.Set(reflect.Zero(v.Type())) - // otherwise, ignore null for primitives/string - } - case 't', 'f': // true, false - value := c == 't' - switch v.Kind() { - default: - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.peekPos() + 1)}) - } - case reflect.Bool: - v.SetBool(value) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(value)) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.peekPos() + 1)}) - } - } - - case '"': // string - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - switch v.Kind() { - default: - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.peekPos() + 1)}) - case reflect.Slice: - if v.Type().Elem().Kind() != reflect.Uint8 { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.peekPos() + 1)}) - break - } - b := make([]byte, base64.StdEncoding.DecodedLen(len(s))) - n, err := base64.StdEncoding.Decode(b, s) - if err != nil { - d.saveError(err) - break - } - v.SetBytes(b[:n]) - case reflect.String: - v.SetString(string(s)) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(string(s))) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.peekPos() + 1)}) - } - } - - default: // number - if c != '-' && (c < '0' || c > '9') { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - s := string(item) - switch v.Kind() { - default: - if v.Kind() == reflect.String && v.Type() == numberType { - v.SetString(s) - if !isValidNumber(s) { - d.error(fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item)) - } - break - } - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(&UnmarshalTypeError{"number", v.Type(), int64(d.peekPos() + 1)}) - } - case reflect.Interface: - n, err := d.convertNumber(s) - if err != nil { - d.saveError(err) - break - } - if v.NumMethod() != 0 { - d.saveError(&UnmarshalTypeError{"number", v.Type(), int64(d.peekPos() + 1)}) - break - } - v.Set(reflect.ValueOf(n)) - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - n, err := strconv.ParseInt(s, 10, 64) - if err != nil || v.OverflowInt(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.peekPos() + 1)}) - break - } - v.SetInt(n) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - n, err := strconv.ParseUint(s, 10, 64) - if err != nil || v.OverflowUint(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.peekPos() + 1)}) - break - } - v.SetUint(n) - - case reflect.Float32, reflect.Float64: - n, err := strconv.ParseFloat(s, v.Type().Bits()) - if err != nil || v.OverflowFloat(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.peekPos() + 1)}) - break - } - v.SetFloat(n) - } - } -} - -// The xxxInterface routines build up a value to be stored -// in an empty interface. They are not strictly necessary, -// but they avoid the weight of reflection in this common case. - -// valueInterface is like value but returns interface{} -func (d *decodeState) valueInterface() interface{} { - switch op := d.peekState(); op { - default: - d.error(errPhase) - panic("unreachable") - case scanBeginArray: - return d.arrayInterface() - case scanBeginObject: - return d.objectInterface() - case scanBeginLiteral: - return d.literalInterface() - } -} - -// arrayInterface is like array but returns []interface{}. -func (d *decodeState) arrayInterface() []interface{} { - var v = make([]interface{}, 0) - d.skipRecord() // skip [ - for { - // Look ahead for ] - can only happen on first iteration. - op := d.peekState() - if op == scanEndArray { - d.skipRecord() - break - } - if op != scanBeginLiteral && op != scanBeginObject && op != scanBeginArray { - d.error(errPhase) - } - - v = append(v, d.valueInterface()) - } - return v -} - -// objectInterface is like object but returns map[string]interface{}. -func (d *decodeState) objectInterface() map[string]interface{} { - m := make(map[string]interface{}) - d.skipRecord() // skip { - for { - // Read opening " of string key or closing }. - op := d.peekState() - if op == scanEndObject { - // closing } - can only happen on first iteration. - d.skipRecord() //skip } - break - } - if op != scanBeginLiteral { - d.error(errPhase) - } - - // Read string key. - start := d.takePos() - op, end := d.takeRecord() - if op != scanEndLiteral { - d.error(errPhase) - } - item := d.data[start : end+1] - key, ok := unquote(item) - if !ok { - d.error(errPhase) - } - - // Read value. - m[key] = d.valueInterface() - - } - return m -} - -// literalInterface is like literal but returns an interface value. -func (d *decodeState) literalInterface() interface{} { - start := d.takePos() - op, end := d.takeRecord() - if op != scanEndLiteral { - d.error(errPhase) - } - item := d.data[start : end+1] - - switch c := item[0]; c { - case 'n': // null - return nil - - case 't', 'f': // true, false - return c == 't' - - case '"': // string - s, ok := unquote(item) - if !ok { - d.error(errPhase) - } - return s - - default: // number - if c != '-' && (c < '0' || c > '9') { - d.error(errPhase) - } - n, err := d.convertNumber(string(item)) - if err != nil { - d.saveError(err) - } - return n - } -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - r, err := strconv.ParseUint(string(s[2:6]), 16, 64) - if err != nil { - return -1 - } - return rune(r) -} - -// unquote converts a quoted JSON string literal s into an actual string t. -// The rules are different than for Go, so cannot use strconv.Unquote. -func unquote(s []byte) (t string, ok bool) { - s, ok = unquoteBytes(s) - t = string(s) - return -} - -func unquoteBytes(s []byte) (t []byte, ok bool) { - if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { - return - } - s = s[1 : len(s)-1] - - // Check for unusual characters. If there are none, - // then no unquoting is needed, so return a slice of the - // original bytes. - r := 0 - for r < len(s) { - c := s[r] - if c == '\\' || c == '"' || c < ' ' { - break - } - if c < utf8.RuneSelf { - r++ - continue - } - rr, size := utf8.DecodeRune(s[r:]) - if rr == utf8.RuneError && size == 1 { - break - } - r += size - } - if r == len(s) { - return s, true - } - - b := make([]byte, len(s)+2*utf8.UTFMax) - w := copy(b, s[0:r]) - for r < len(s) { - // Out of room? Can only happen if s is full of - // malformed UTF-8 and we're replacing each - // byte with RuneError. - if w >= len(b)-2*utf8.UTFMax { - nb := make([]byte, (len(b)+utf8.UTFMax)*2) - copy(nb, b[0:w]) - b = nb - } - switch c := s[r]; { - case c == '\\': - r++ - if r >= len(s) { - return - } - switch s[r] { - default: - return - case '"', '\\', '/', '\'': - b[w] = s[r] - r++ - w++ - case 'b': - b[w] = '\b' - r++ - w++ - case 'f': - b[w] = '\f' - r++ - w++ - case 'n': - b[w] = '\n' - r++ - w++ - case 'r': - b[w] = '\r' - r++ - w++ - case 't': - b[w] = '\t' - r++ - w++ - case 'u': - r-- - rr := getu4(s[r:]) - if rr < 0 { - return - } - r += 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(s[r:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - // A valid pair; consume. - r += 6 - w += utf8.EncodeRune(b[w:], dec) - break - } - // Invalid surrogate; fall back to replacement rune. - rr = unicode.ReplacementChar - } - w += utf8.EncodeRune(b[w:], rr) - } - - // Quote, control characters are invalid. - case c == '"', c < ' ': - return - - // ASCII - case c < utf8.RuneSelf: - b[w] = c - r++ - w++ - - // Coerce to well-formed UTF-8. - default: - rr, size := utf8.DecodeRune(s[r:]) - r += size - w += utf8.EncodeRune(b[w:], rr) - } - } - return b[0:w], true -} diff --git a/vendor/github.com/intel-go/fastjson/decode_test.go b/vendor/github.com/intel-go/fastjson/decode_test.go deleted file mode 100644 index 9f8e59f..0000000 --- a/vendor/github.com/intel-go/fastjson/decode_test.go +++ /dev/null @@ -1,1486 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package fastjson - -import ( - "bytes" - "encoding" - "fmt" - "image" - "net" - "reflect" - "strings" - "testing" - "time" -) - -type T struct { - X string - Y int - Z int `json:"-"` -} - -type U struct { - Alphabet string `json:"alpha"` -} - -type V struct { - F1 interface{} - F2 int32 - F3 Number -} - -// ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and -// without UseNumber -var ifaceNumAsFloat64 = map[string]interface{}{ - "k1": float64(1), - "k2": "s", - "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)}, - "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)}, -} - -var ifaceNumAsNumber = map[string]interface{}{ - "k1": Number("1"), - "k2": "s", - "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")}, - "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")}, -} - -type tx struct { - x int -} - -// A type that can unmarshal itself. - -type unmarshaler struct { - T bool -} - -func (u *unmarshaler) UnmarshalJSON(b []byte) error { - *u = unmarshaler{true} // All we need to see that UnmarshalJSON is called. - return nil -} - -type ustruct struct { - M unmarshaler -} - -type unmarshalerText struct { - T bool -} - -// needed for re-marshaling tests -func (u *unmarshalerText) MarshalText() ([]byte, error) { - return []byte(""), nil -} - -func (u *unmarshalerText) UnmarshalText(b []byte) error { - *u = unmarshalerText{true} // All we need to see that UnmarshalText is called. - return nil -} - -var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil) - -type ustructText struct { - M unmarshalerText -} - -var ( - um0, um1 unmarshaler // target2 of unmarshaling - ump = &um1 - umtrue = unmarshaler{true} - umslice = []unmarshaler{{true}} - umslicep = new([]unmarshaler) - umstruct = ustruct{unmarshaler{true}} - - um0T, um1T unmarshalerText // target2 of unmarshaling - umpT = &um1T - umtrueT = unmarshalerText{true} - umsliceT = []unmarshalerText{{true}} - umslicepT = new([]unmarshalerText) - umstructT = ustructText{unmarshalerText{true}} -) - -// Test data structures for anonymous fields. - -type Point struct { - Z int -} - -type Top struct { - Level0 int - Embed0 - *Embed0a - *Embed0b `json:"e,omitempty"` // treated as named - Embed0c `json:"-"` // ignored - Loop - Embed0p // has Point with X, Y, used - Embed0q // has Point with Z, used - embed // contains exported field -} - -type Embed0 struct { - Level1a int // overridden by Embed0a's Level1a with json tag - Level1b int // used because Embed0a's Level1b is renamed - Level1c int // used because Embed0a's Level1c is ignored - Level1d int // annihilated by Embed0a's Level1d - Level1e int `json:"x"` // annihilated by Embed0a.Level1e -} - -type Embed0a struct { - Level1a int `json:"Level1a,omitempty"` - Level1b int `json:"LEVEL1B,omitempty"` - Level1c int `json:"-"` - Level1d int // annihilated by Embed0's Level1d - Level1f int `json:"x"` // annihilated by Embed0's Level1e -} - -type Embed0b Embed0 - -type Embed0c Embed0 - -type Embed0p struct { - image.Point -} - -type Embed0q struct { - Point -} - -type embed struct { - Q int -} - -type Loop struct { - Loop1 int `json:",omitempty"` - Loop2 int `json:",omitempty"` - *Loop -} - -// From reflect test: -// The X in S6 and S7 annihilate, but they also block the X in S8.S9. -type S5 struct { - S6 - S7 - S8 -} - -type S6 struct { - X int -} - -type S7 S6 - -type S8 struct { - S9 -} - -type S9 struct { - X int - Y int -} - -// From reflect test: -// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. -type S10 struct { - S11 - S12 - S13 -} - -type S11 struct { - S6 -} - -type S12 struct { - S6 -} - -type S13 struct { - S8 -} - -type unmarshalTest struct { - in string - ptr interface{} - out interface{} - err error - useNumber bool -} - -type Ambig struct { - // Given "hello", the first match should win. - First int `json:"HELLO"` - Second int `json:"Hello"` -} - -type XYZ struct { - X interface{} - Y interface{} - Z interface{} -} - -func sliceAddr(x []int) *[]int { return &x } -func mapAddr(x map[string]int) *map[string]int { return &x } - -var unmarshalTests = []unmarshalTest{ - // basic types - {in: `true`, ptr: new(bool), out: true}, - {in: `1`, ptr: new(int), out: 1}, - {in: `1.2`, ptr: new(float64), out: 1.2}, - {in: `-5`, ptr: new(int16), out: int16(-5)}, - {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true}, - {in: `2`, ptr: new(Number), out: Number("2")}, - {in: `2`, ptr: new(interface{}), out: float64(2.0)}, - {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true}, - {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"}, - {in: `"http:\/\/"`, ptr: new(string), out: "http://"}, - {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"}, - {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"}, - {in: "null", ptr: new(interface{}), out: nil}, - {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf(""), 7}}, - {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, - {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}}, - {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true}, - - // raw values with whitespace - {in: "\n true ", ptr: new(bool), out: true}, - {in: "\t 1 ", ptr: new(int), out: 1}, - {in: "\r 1.2 ", ptr: new(float64), out: 1.2}, - {in: "\t -5 \n", ptr: new(int16), out: int16(-5)}, - {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"}, - - // Z has a "-" tag. - {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}}, - - {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}}, - {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}}, - {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}}, - - // syntax errors - {in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", 17}}, - {in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", 9}}, - {in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true}, - - // raw value errors - {in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " 42 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 5}}, - {in: "\x01 true", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " false \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 8}}, - {in: "\x01 1.2", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " 3.4 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 6}}, - {in: "\x01 \"string\"", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " \"string\" \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 11}}, - - // array tests - {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}}, - {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}}, - {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}}, - - // empty array to interface test - {in: `[]`, ptr: new([]interface{}), out: []interface{}{}}, - {in: `null`, ptr: new([]interface{}), out: []interface{}(nil)}, - {in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}}, - {in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}}, - - // composite tests - {in: allValueIndent, ptr: new(All), out: allValue}, - {in: allValueCompact, ptr: new(All), out: allValue}, - {in: allValueIndent, ptr: new(*All), out: &allValue}, - {in: allValueCompact, ptr: new(*All), out: &allValue}, - {in: pallValueIndent, ptr: new(All), out: pallValue}, - {in: pallValueCompact, ptr: new(All), out: pallValue}, - {in: pallValueIndent, ptr: new(*All), out: &pallValue}, - {in: pallValueCompact, ptr: new(*All), out: &pallValue}, - - // unmarshal interface test - {in: `{"T":false}`, ptr: &um0, out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called - {in: `{"T":false}`, ptr: &ump, out: &umtrue}, - {in: `[{"T":false}]`, ptr: &umslice, out: umslice}, - {in: `[{"T":false}]`, ptr: &umslicep, out: &umslice}, - {in: `{"M":{"T":false}}`, ptr: &umstruct, out: umstruct}, - - // UnmarshalText interface test - {in: `"X"`, ptr: &um0T, out: umtrueT}, // use "false" so test will fail if custom unmarshaler is not called - {in: `"X"`, ptr: &umpT, out: &umtrueT}, - {in: `["X"]`, ptr: &umsliceT, out: umsliceT}, - {in: `["X"]`, ptr: &umslicepT, out: &umsliceT}, - {in: `{"M":"X"}`, ptr: &umstructT, out: umstructT}, - - // Overwriting of data. - // This is different from package xml, but it's what we've always done. - // Now documented and tested. - {in: `[2]`, ptr: sliceAddr([]int{1}), out: []int{2}}, - {in: `{"key": 2}`, ptr: mapAddr(map[string]int{"old": 0, "key": 1}), out: map[string]int{"key": 2}}, - - { - in: `{ - "Level0": 1, - "Level1b": 2, - "Level1c": 3, - "x": 4, - "Level1a": 5, - "LEVEL1B": 6, - "e": { - "Level1a": 8, - "Level1b": 9, - "Level1c": 10, - "Level1d": 11, - "x": 12 - }, - "Loop1": 13, - "Loop2": 14, - "X": 15, - "Y": 16, - "Z": 17, - "Q": 18 - }`, - ptr: new(Top), - out: Top{ - Level0: 1, - Embed0: Embed0{ - Level1b: 2, - Level1c: 3, - }, - Embed0a: &Embed0a{ - Level1a: 5, - Level1b: 6, - }, - Embed0b: &Embed0b{ - Level1a: 8, - Level1b: 9, - Level1c: 10, - Level1d: 11, - Level1e: 12, - }, - Loop: Loop{ - Loop1: 13, - Loop2: 14, - }, - Embed0p: Embed0p{ - Point: image.Point{X: 15, Y: 16}, - }, - Embed0q: Embed0q{ - Point: Point{Z: 17}, - }, - embed: embed{ - Q: 18, - }, - }, - }, - { - in: `{"hello": 1}`, - ptr: new(Ambig), - out: Ambig{First: 1}, - }, - - { - in: `{"X": 1,"Y":2}`, - ptr: new(S5), - out: S5{S8: S8{S9: S9{Y: 2}}}, - }, - { - in: `{"X": 1,"Y":2}`, - ptr: new(S10), - out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}}, - }, - - // invalid UTF-8 is coerced to valid UTF-8. - { - in: "\"hello\xffworld\"", - ptr: new(string), - out: "hello\ufffdworld", - }, - { - in: "\"hello\xc2\xc2world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\xc2\xffworld\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\\ud800world\"", - ptr: new(string), - out: "hello\ufffdworld", - }, - { - in: "\"hello\\ud800\\ud800world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\\ud800\\ud800world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\xed\xa0\x80\xed\xb0\x80world\"", - ptr: new(string), - out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld", - }, - - // issue 8305 - { - in: `{"2009-11-10T23:00:00Z": "hello world"}`, - ptr: &map[time.Time]string{}, - err: &UnmarshalTypeError{"object", reflect.TypeOf(map[time.Time]string{}), 1}, - }, -} - -func TestMarshal(t *testing.T) { - b, err := Marshal(allValue) - if err != nil { - t.Fatalf("Marshal allValue: %v", err) - } - if string(b) != allValueCompact { - t.Errorf("Marshal allValueCompact") - diff(t, b, []byte(allValueCompact)) - return - } - - b, err = Marshal(pallValue) - if err != nil { - t.Fatalf("Marshal pallValue: %v", err) - } - if string(b) != pallValueCompact { - t.Errorf("Marshal pallValueCompact") - diff(t, b, []byte(pallValueCompact)) - return - } -} - -var badUTF8 = []struct { - in, out string -}{ - {"hello\xffworld", `"hello\ufffdworld"`}, - {"", `""`}, - {"\xff", `"\ufffd"`}, - {"\xff\xff", `"\ufffd\ufffd"`}, - {"a\xffb", `"a\ufffdb"`}, - {"\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`}, -} - -func TestMarshalBadUTF8(t *testing.T) { - for _, tt := range badUTF8 { - b, err := Marshal(tt.in) - if string(b) != tt.out || err != nil { - t.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt.in, b, err, tt.out) - } - } -} - -func TestMarshalNumberZeroVal(t *testing.T) { - var n Number - out, err := Marshal(n) - if err != nil { - t.Fatal(err) - } - outStr := string(out) - if outStr != "0" { - t.Fatalf("Invalid zero val for Number: %q", outStr) - } -} - -func TestMarshalEmbeds(t *testing.T) { - top := &Top{ - Level0: 1, - Embed0: Embed0{ - Level1b: 2, - Level1c: 3, - }, - Embed0a: &Embed0a{ - Level1a: 5, - Level1b: 6, - }, - Embed0b: &Embed0b{ - Level1a: 8, - Level1b: 9, - Level1c: 10, - Level1d: 11, - Level1e: 12, - }, - Loop: Loop{ - Loop1: 13, - Loop2: 14, - }, - Embed0p: Embed0p{ - Point: image.Point{X: 15, Y: 16}, - }, - Embed0q: Embed0q{ - Point: Point{Z: 17}, - }, - embed: embed{ - Q: 18, - }, - } - b, err := Marshal(top) - if err != nil { - t.Fatal(err) - } - want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17,\"Q\":18}" - if string(b) != want { - t.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b, want) - } -} - -func TestUnmarshal(t *testing.T) { - for i, tt := range unmarshalTests { - var scan scanner - in := []byte(tt.in) - if err := checkValid(in, &scan); err != nil { - if !reflect.DeepEqual(err, tt.err) { - t.Errorf("#%d: checkValid: %#v", i, err) - continue - } - } - if tt.ptr == nil { - continue - } - - // v = new(right-type) - v := reflect.New(reflect.TypeOf(tt.ptr).Elem()) - dec := NewDecoder(bytes.NewReader(in)) - if tt.useNumber { - dec.UseNumber() - } - if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) { - t.Errorf("#%d: %v, want %v", i, err, tt.err) - continue - } else if err != nil { - continue - } - if !reflect.DeepEqual(v.Elem().Interface(), tt.out) { - t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out) - data, _ := Marshal(v.Elem().Interface()) - println(string(data)) - data, _ = Marshal(tt.out) - println(string(data)) - continue - } - - // Check round trip. - if tt.err == nil { - enc, err := Marshal(v.Interface()) - if err != nil { - t.Errorf("#%d: error re-marshaling: %v", i, err) - continue - } - vv := reflect.New(reflect.TypeOf(tt.ptr).Elem()) - dec = NewDecoder(bytes.NewReader(enc)) - if tt.useNumber { - dec.UseNumber() - } - if err := dec.Decode(vv.Interface()); err != nil { - t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err) - continue - } - if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) { - t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface()) - t.Errorf(" In: %q", strings.Map(noSpace, string(in))) - t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc))) - continue - } - } - } -} - -func TestUnmarshalMarshal(t *testing.T) { - initBig() - var v interface{} - if err := Unmarshal(jsonBig, &v); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - b, err := Marshal(v) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(jsonBig, b) { - t.Errorf("Marshal jsonBig") - diff(t, b, jsonBig) - return - } -} - -var numberTests = []struct { - in string - i int64 - intErr string - f float64 - floatErr string -}{ - {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1}, - {in: "-12", i: -12, f: -12.0}, - {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"}, -} - -// Independent of Decode, basic coverage of the accessors in Number -func TestNumberAccessors(t *testing.T) { - for _, tt := range numberTests { - n := Number(tt.in) - if s := n.String(); s != tt.in { - t.Errorf("Number(%q).String() is %q", tt.in, s) - } - if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i { - t.Errorf("Number(%q).Int64() is %d", tt.in, i) - } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) { - t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err) - } - if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f { - t.Errorf("Number(%q).Float64() is %g", tt.in, f) - } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) { - t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err) - } - } -} - -func TestLargeByteSlice(t *testing.T) { - s0 := make([]byte, 2000) - for i := range s0 { - s0[i] = byte(i) - } - b, err := Marshal(s0) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - var s1 []byte - if err := Unmarshal(b, &s1); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !bytes.Equal(s0, s1) { - t.Errorf("Marshal large byte slice") - diff(t, s0, s1) - } -} - -type Xint struct { - X int -} - -func TestUnmarshalInterface(t *testing.T) { - var xint Xint - var i interface{} = &xint - if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if xint.X != 1 { - t.Fatalf("Did not write to xint") - } -} - -func TestUnmarshalPtrPtr(t *testing.T) { - var xint Xint - pxint := &xint - if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if xint.X != 1 { - t.Fatalf("Did not write to xint") - } -} - -func TestEscape(t *testing.T) { - const input = `"foobar"` + " [\u2028 \u2029]" - const expected = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"` - b, err := Marshal(input) - if err != nil { - t.Fatalf("Marshal error: %v", err) - } - if s := string(b); s != expected { - t.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input, s, expected) - } -} - -// WrongString is a struct that's misusing the ,string modifier. -type WrongString struct { - Message string `json:"result,string"` -} - -type wrongStringTest struct { - in, err string -} - -var wrongStringTests = []wrongStringTest{ - {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`}, - {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`}, - {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`}, - {`{"result":123}`, `json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string`}, -} - -// If people misuse the ,string modifier, the error message should be -// helpful, telling the user that they're doing it wrong. -func TestErrorMessageFromMisusedString(t *testing.T) { - for n, tt := range wrongStringTests { - r := strings.NewReader(tt.in) - var s WrongString - err := NewDecoder(r).Decode(&s) - got := fmt.Sprintf("%v", err) - if got != tt.err { - t.Errorf("%d. got err = %q, want %q", n, got, tt.err) - } - } -} - -func noSpace(c rune) rune { - if isSpace(byte(c)) { //only used for ascii - return -1 - } - return c -} - -type All struct { - Bool bool - Int int - Int8 int8 - Int16 int16 - Int32 int32 - Int64 int64 - Uint uint - Uint8 uint8 - Uint16 uint16 - Uint32 uint32 - Uint64 uint64 - Uintptr uintptr - Float32 float32 - Float64 float64 - - Foo string `json:"bar"` - Foo2 string `json:"bar2,dummyopt"` - - IntStr int64 `json:",string"` - - PBool *bool - PInt *int - PInt8 *int8 - PInt16 *int16 - PInt32 *int32 - PInt64 *int64 - PUint *uint - PUint8 *uint8 - PUint16 *uint16 - PUint32 *uint32 - PUint64 *uint64 - PUintptr *uintptr - PFloat32 *float32 - PFloat64 *float64 - - String string - PString *string - - Map map[string]Small - MapP map[string]*Small - PMap *map[string]Small - PMapP *map[string]*Small - - EmptyMap map[string]Small - NilMap map[string]Small - - Slice []Small - SliceP []*Small - PSlice *[]Small - PSliceP *[]*Small - - EmptySlice []Small - NilSlice []Small - - StringSlice []string - ByteSlice []byte - - Small Small - PSmall *Small - PPSmall **Small - - Interface interface{} - PInterface *interface{} - - unexported int -} - -type Small struct { - Tag string -} - -var allValue = All{ - Bool: true, - Int: 2, - Int8: 3, - Int16: 4, - Int32: 5, - Int64: 6, - Uint: 7, - Uint8: 8, - Uint16: 9, - Uint32: 10, - Uint64: 11, - Uintptr: 12, - Float32: 14.1, - Float64: 15.1, - Foo: "foo", - Foo2: "foo2", - IntStr: 42, - String: "16", - Map: map[string]Small{ - "17": {Tag: "tag17"}, - "18": {Tag: "tag18"}, - }, - MapP: map[string]*Small{ - "19": {Tag: "tag19"}, - "20": nil, - }, - EmptyMap: map[string]Small{}, - Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}}, - SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}}, - EmptySlice: []Small{}, - StringSlice: []string{"str24", "str25", "str26"}, - ByteSlice: []byte{27, 28, 29}, - Small: Small{Tag: "tag30"}, - PSmall: &Small{Tag: "tag31"}, - Interface: 5.2, -} - -var pallValue = All{ - PBool: &allValue.Bool, - PInt: &allValue.Int, - PInt8: &allValue.Int8, - PInt16: &allValue.Int16, - PInt32: &allValue.Int32, - PInt64: &allValue.Int64, - PUint: &allValue.Uint, - PUint8: &allValue.Uint8, - PUint16: &allValue.Uint16, - PUint32: &allValue.Uint32, - PUint64: &allValue.Uint64, - PUintptr: &allValue.Uintptr, - PFloat32: &allValue.Float32, - PFloat64: &allValue.Float64, - PString: &allValue.String, - PMap: &allValue.Map, - PMapP: &allValue.MapP, - PSlice: &allValue.Slice, - PSliceP: &allValue.SliceP, - PPSmall: &allValue.PSmall, - PInterface: &allValue.Interface, -} - -var allValueIndent = `{ - "Bool": true, - "Int": 2, - "Int8": 3, - "Int16": 4, - "Int32": 5, - "Int64": 6, - "Uint": 7, - "Uint8": 8, - "Uint16": 9, - "Uint32": 10, - "Uint64": 11, - "Uintptr": 12, - "Float32": 14.1, - "Float64": 15.1, - "bar": "foo", - "bar2": "foo2", - "IntStr": "42", - "PBool": null, - "PInt": null, - "PInt8": null, - "PInt16": null, - "PInt32": null, - "PInt64": null, - "PUint": null, - "PUint8": null, - "PUint16": null, - "PUint32": null, - "PUint64": null, - "PUintptr": null, - "PFloat32": null, - "PFloat64": null, - "String": "16", - "PString": null, - "Map": { - "17": { - "Tag": "tag17" - }, - "18": { - "Tag": "tag18" - } - }, - "MapP": { - "19": { - "Tag": "tag19" - }, - "20": null - }, - "PMap": null, - "PMapP": null, - "EmptyMap": {}, - "NilMap": null, - "Slice": [ - { - "Tag": "tag20" - }, - { - "Tag": "tag21" - } - ], - "SliceP": [ - { - "Tag": "tag22" - }, - null, - { - "Tag": "tag23" - } - ], - "PSlice": null, - "PSliceP": null, - "EmptySlice": [], - "NilSlice": null, - "StringSlice": [ - "str24", - "str25", - "str26" - ], - "ByteSlice": "Gxwd", - "Small": { - "Tag": "tag30" - }, - "PSmall": { - "Tag": "tag31" - }, - "PPSmall": null, - "Interface": 5.2, - "PInterface": null -}` - -var allValueCompact = strings.Map(noSpace, allValueIndent) - -var pallValueIndent = `{ - "Bool": false, - "Int": 0, - "Int8": 0, - "Int16": 0, - "Int32": 0, - "Int64": 0, - "Uint": 0, - "Uint8": 0, - "Uint16": 0, - "Uint32": 0, - "Uint64": 0, - "Uintptr": 0, - "Float32": 0, - "Float64": 0, - "bar": "", - "bar2": "", - "IntStr": "0", - "PBool": true, - "PInt": 2, - "PInt8": 3, - "PInt16": 4, - "PInt32": 5, - "PInt64": 6, - "PUint": 7, - "PUint8": 8, - "PUint16": 9, - "PUint32": 10, - "PUint64": 11, - "PUintptr": 12, - "PFloat32": 14.1, - "PFloat64": 15.1, - "String": "", - "PString": "16", - "Map": null, - "MapP": null, - "PMap": { - "17": { - "Tag": "tag17" - }, - "18": { - "Tag": "tag18" - } - }, - "PMapP": { - "19": { - "Tag": "tag19" - }, - "20": null - }, - "EmptyMap": null, - "NilMap": null, - "Slice": null, - "SliceP": null, - "PSlice": [ - { - "Tag": "tag20" - }, - { - "Tag": "tag21" - } - ], - "PSliceP": [ - { - "Tag": "tag22" - }, - null, - { - "Tag": "tag23" - } - ], - "EmptySlice": null, - "NilSlice": null, - "StringSlice": null, - "ByteSlice": null, - "Small": { - "Tag": "" - }, - "PSmall": null, - "PPSmall": { - "Tag": "tag31" - }, - "Interface": null, - "PInterface": 5.2 -}` - -var pallValueCompact = strings.Map(noSpace, pallValueIndent) - -func TestRefUnmarshal(t *testing.T) { - type S struct { - // Ref is defined in encode_test.go. - R0 Ref - R1 *Ref - R2 RefText - R3 *RefText - } - want := S{ - R0: 12, - R1: new(Ref), - R2: 13, - R3: new(RefText), - } - *want.R1 = 12 - *want.R3 = 13 - - var got S - if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got %+v, want %+v", got, want) - } -} - -// Test that the empty string doesn't panic decoding when ,string is specified -// Issue 3450 -func TestEmptyString(t *testing.T) { - type T2 struct { - Number1 int `json:",string"` - Number2 int `json:",string"` - } - data := `{"Number1":"1", "Number2":""}` - dec := NewDecoder(strings.NewReader(data)) - var t2 T2 - err := dec.Decode(&t2) - if err == nil { - t.Fatal("Decode: did not return error") - } - if t2.Number1 != 1 { - t.Fatal("Decode: did not set Number1") - } -} - -// Test that a null for ,string is not replaced with the previous quoted string (issue 7046). -// It should also not be an error (issue 2540, issue 8587). -func TestNullString(t *testing.T) { - type T struct { - A int `json:",string"` - B int `json:",string"` - C *int `json:",string"` - } - data := []byte(`{"A": "1", "B": null, "C": null}`) - var s T - s.B = 1 - s.C = new(int) - *s.C = 2 - err := Unmarshal(data, &s) - if err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if s.B != 1 || s.C != nil { - t.Fatalf("after Unmarshal, s.B=%d, s.C=%p, want 1, nil", s.B, s.C) - } -} - -func intp(x int) *int { - p := new(int) - *p = x - return p -} - -func intpp(x *int) **int { - pp := new(*int) - *pp = x - return pp -} - -var interfaceSetTests = []struct { - pre interface{} - json string - post interface{} -}{ - {"foo", `"bar"`, "bar"}, - {"foo", `2`, 2.0}, - {"foo", `true`, true}, - {"foo", `null`, nil}, - - {nil, `null`, nil}, - {new(int), `null`, nil}, - {(*int)(nil), `null`, nil}, - {new(*int), `null`, new(*int)}, - {(**int)(nil), `null`, nil}, - {intp(1), `null`, nil}, - {intpp(nil), `null`, intpp(nil)}, - {intpp(intp(1)), `null`, intpp(nil)}, -} - -func TestInterfaceSet(t *testing.T) { - for _, tt := range interfaceSetTests { - b := struct{ X interface{} }{tt.pre} - blob := `{"X":` + tt.json + `}` - if err := Unmarshal([]byte(blob), &b); err != nil { - t.Errorf("Unmarshal %#q: %v", blob, err) - continue - } - if !reflect.DeepEqual(b.X, tt.post) { - t.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob, tt.pre, b.X, tt.post) - } - } -} - -// JSON null values should be ignored for primitives and string values instead of resulting in an error. -// Issue 2540 -func TestUnmarshalNulls(t *testing.T) { - jsonData := []byte(`{ - "Bool" : null, - "Int" : null, - "Int8" : null, - "Int16" : null, - "Int32" : null, - "Int64" : null, - "Uint" : null, - "Uint8" : null, - "Uint16" : null, - "Uint32" : null, - "Uint64" : null, - "Float32" : null, - "Float64" : null, - "String" : null}`) - - nulls := All{ - Bool: true, - Int: 2, - Int8: 3, - Int16: 4, - Int32: 5, - Int64: 6, - Uint: 7, - Uint8: 8, - Uint16: 9, - Uint32: 10, - Uint64: 11, - Float32: 12.1, - Float64: 13.1, - String: "14"} - - err := Unmarshal(jsonData, &nulls) - if err != nil { - t.Errorf("Unmarshal of null values failed: %v", err) - } - if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 || - nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 || - nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" { - - t.Errorf("Unmarshal of null values affected primitives") - } -} - -func TestStringKind(t *testing.T) { - type stringKind string - - var m1, m2 map[stringKind]int - m1 = map[stringKind]int{ - "foo": 42, - } - - data, err := Marshal(m1) - if err != nil { - t.Errorf("Unexpected error marshaling: %v", err) - } - - err = Unmarshal(data, &m2) - if err != nil { - t.Errorf("Unexpected error unmarshaling: %v", err) - } - - if !reflect.DeepEqual(m1, m2) { - t.Error("Items should be equal after encoding and then decoding") - } -} - -// Custom types with []byte as underlying type could not be marshalled -// and then unmarshalled. -// Issue 8962. -func TestByteKind(t *testing.T) { - type byteKind []byte - - a := byteKind("hello") - - data, err := Marshal(a) - if err != nil { - t.Error(err) - } - var b byteKind - err = Unmarshal(data, &b) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(a, b) { - t.Errorf("expected %v == %v", a, b) - } -} - -// The fix for issue 8962 introduced a regression. -// Issue 12921. -func TestSliceOfCustomByte(t *testing.T) { - type Uint8 uint8 - - a := []Uint8("hello") - - data, err := Marshal(a) - if err != nil { - t.Fatal(err) - } - var b []Uint8 - err = Unmarshal(data, &b) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(a, b) { - t.Fatal("expected %v == %v", a, b) - } -} - -var decodeTypeErrorTests = []struct { - dest interface{} - src string -}{ - {new(string), `{"user": "name"}`}, // issue 4628. - {new(error), `{}`}, // issue 4222 - {new(error), `[]`}, - {new(error), `""`}, - {new(error), `123`}, - {new(error), `true`}, -} - -func TestUnmarshalTypeError(t *testing.T) { - for _, item := range decodeTypeErrorTests { - err := Unmarshal([]byte(item.src), item.dest) - if _, ok := err.(*UnmarshalTypeError); !ok { - t.Errorf("expected type error for Unmarshal(%q, type %T): got %T", - item.src, item.dest, err) - } - } -} - -var unmarshalSyntaxTests = []string{ - "tru", - "fals", - "nul", - "123e", - `"hello`, - `[1,2,3`, - `{"key":1`, - `{"key":1,`, -} - -func TestUnmarshalSyntax(t *testing.T) { - var x interface{} - for _, src := range unmarshalSyntaxTests { - err := Unmarshal([]byte(src), &x) - if _, ok := err.(*SyntaxError); !ok { - t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err) - } - } -} - -// Test handling of unexported fields that should be ignored. -// Issue 4660 -type unexportedFields struct { - Name string - m map[string]interface{} `json:"-"` - m2 map[string]interface{} `json:"abcd"` -} - -func TestUnmarshalUnexported(t *testing.T) { - input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}}` - want := &unexportedFields{Name: "Bob"} - - out := &unexportedFields{} - err := Unmarshal([]byte(input), out) - if err != nil { - t.Errorf("got error %v, expected nil", err) - } - if !reflect.DeepEqual(out, want) { - t.Errorf("got %q, want %q", out, want) - } -} - -// Time3339 is a time.Time which encodes to and from JSON -// as an RFC 3339 time in UTC. -type Time3339 time.Time - -func (t *Time3339) UnmarshalJSON(b []byte) error { - if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' { - return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b) - } - tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1])) - if err != nil { - return err - } - *t = Time3339(tm) - return nil -} - -func TestUnmarshalJSONLiteralError(t *testing.T) { - var t3 Time3339 - err := Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3) - if err == nil { - t.Fatalf("expected error; got time %v", time.Time(t3)) - } - if !strings.Contains(err.Error(), "range") { - t.Errorf("got err = %v; want out of range error", err) - } -} - -// Test that extra object elements in an array do not result in a -// "data changing underfoot" error. -// Issue 3717 -func TestSkipArrayObjects(t *testing.T) { - json := `[{}]` - var dest [0]interface{} - - err := Unmarshal([]byte(json), &dest) - if err != nil { - t.Errorf("got error %q, want nil", err) - } -} - -// Test semantics of pre-filled struct fields and pre-filled map fields. -// Issue 4900. -func TestPrefilled(t *testing.T) { - ptrToMap := func(m map[string]interface{}) *map[string]interface{} { return &m } - - // Values here change, cannot reuse table across runs. - var prefillTests = []struct { - in string - ptr interface{} - out interface{} - }{ - { - in: `{"X": 1, "Y": 2}`, - ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5}, - out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5}, - }, - { - in: `{"X": 1, "Y": 2}`, - ptr: ptrToMap(map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}), - out: ptrToMap(map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}), - }, - } - - for _, tt := range prefillTests { - ptrstr := fmt.Sprintf("%v", tt.ptr) - err := Unmarshal([]byte(tt.in), tt.ptr) // tt.ptr edited here - if err != nil { - t.Errorf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(tt.ptr, tt.out) { - t.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt.in, ptrstr, tt.ptr, tt.out) - } - } -} - -var invalidUnmarshalTests = []struct { - v interface{} - want string -}{ - {nil, "json: Unmarshal(nil)"}, - {struct{}{}, "json: Unmarshal(non-pointer struct {})"}, - {(*int)(nil), "json: Unmarshal(nil *int)"}, -} - -func TestInvalidUnmarshal(t *testing.T) { - buf := []byte(`{"a":"1"}`) - for _, tt := range invalidUnmarshalTests { - err := Unmarshal(buf, tt.v) - if err == nil { - t.Errorf("Unmarshal expecting error, got nil") - continue - } - if got := err.Error(); got != tt.want { - t.Errorf("Unmarshal = %q; want %q", got, tt.want) - } - } -} - -var invalidUnmarshalTextTests = []struct { - v interface{} - want string -}{ - {nil, "json: Unmarshal(nil)"}, - {struct{}{}, "json: Unmarshal(non-pointer struct {})"}, - {(*int)(nil), "json: Unmarshal(nil *int)"}, - {new(net.IP), "json: cannot unmarshal string into Go value of type *net.IP"}, -} - -func TestInvalidUnmarshalText(t *testing.T) { - buf := []byte(`123`) - for _, tt := range invalidUnmarshalTextTests { - err := Unmarshal(buf, tt.v) - if err == nil { - t.Errorf("Unmarshal expecting error, got nil") - continue - } - if got := err.Error(); got != tt.want { - t.Errorf("Unmarshal = %q; want %q", got, tt.want) - } - } -} - -// Test that string option is ignored for invalid types. -// Issue 9812. -func TestInvalidStringOption(t *testing.T) { - num := 0 - item := struct { - T time.Time `json:",string"` - M map[string]string `json:",string"` - S []string `json:",string"` - A [1]string `json:",string"` - I interface{} `json:",string"` - P *int `json:",string"` - }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num} - - data, err := Marshal(item) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - err = Unmarshal(data, &item) - if err != nil { - t.Fatalf("Unmarshal: %v", err) - } -} diff --git a/vendor/github.com/intel-go/fastjson/encode.go b/vendor/github.com/intel-go/fastjson/encode.go deleted file mode 100644 index bdd3787..0000000 --- a/vendor/github.com/intel-go/fastjson/encode.go +++ /dev/null @@ -1,1199 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package json implements encoding and decoding of JSON objects as defined in -// RFC 4627. The mapping between JSON objects and Go values is described -// in the documentation for the Marshal and Unmarshal functions. -// -// See "JSON and Go" for an introduction to this package: -// https://golang.org/doc/articles/json_and_go.html -package fastjson - -import ( - "bytes" - "encoding" - "encoding/base64" - "fmt" - "math" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// Marshal returns the JSON encoding of v. -// -// Marshal traverses the value v recursively. -// If an encountered value implements the Marshaler interface -// and is not a nil pointer, Marshal calls its MarshalJSON method -// to produce JSON. If no MarshalJSON method is present but the -// value implements encoding.TextMarshaler instead, Marshal calls -// its MarshalText method. -// The nil pointer exception is not strictly necessary -// but mimics a similar, necessary exception in the behavior of -// UnmarshalJSON. -// -// Otherwise, Marshal uses the following type-dependent default encodings: -// -// Boolean values encode as JSON booleans. -// -// Floating point, integer, and Number values encode as JSON numbers. -// -// String values encode as JSON strings coerced to valid UTF-8, -// replacing invalid bytes with the Unicode replacement rune. -// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" -// to keep some browsers from misinterpreting JSON output as HTML. -// Ampersand "&" is also escaped to "\u0026" for the same reason. -// -// Array and slice values encode as JSON arrays, except that -// []byte encodes as a base64-encoded string, and a nil slice -// encodes as the null JSON object. -// -// Struct values encode as JSON objects. Each exported struct field -// becomes a member of the object unless -// - the field's tag is "-", or -// - the field is empty and its tag specifies the "omitempty" option. -// The empty values are false, 0, any -// nil pointer or interface value, and any array, slice, map, or string of -// length zero. The object's default key string is the struct field name -// but can be specified in the struct field's tag value. The "json" key in -// the struct field's tag value is the key name, followed by an optional comma -// and options. Examples: -// -// // Field is ignored by this package. -// Field int `json:"-"` -// -// // Field appears in JSON as key "myName". -// Field int `json:"myName"` -// -// // Field appears in JSON as key "myName" and -// // the field is omitted from the object if its value is empty, -// // as defined above. -// Field int `json:"myName,omitempty"` -// -// // Field appears in JSON as key "Field" (the default), but -// // the field is skipped if empty. -// // Note the leading comma. -// Field int `json:",omitempty"` -// -// The "string" option signals that a field is stored as JSON inside a -// JSON-encoded string. It applies only to fields of string, floating point, -// integer, or boolean types. This extra level of encoding is sometimes used -// when communicating with JavaScript programs: -// -// Int64String int64 `json:",string"` -// -// The key name will be used if it's a non-empty string consisting of -// only Unicode letters, digits, dollar signs, percent signs, hyphens, -// underscores and slashes. -// -// Anonymous struct fields are usually marshaled as if their inner exported fields -// were fields in the outer struct, subject to the usual Go visibility rules amended -// as described in the next paragraph. -// An anonymous struct field with a name given in its JSON tag is treated as -// having that name, rather than being anonymous. -// An anonymous struct field of interface type is treated the same as having -// that type as its name, rather than being anonymous. -// -// The Go visibility rules for struct fields are amended for JSON when -// deciding which field to marshal or unmarshal. If there are -// multiple fields at the same level, and that level is the least -// nested (and would therefore be the nesting level selected by the -// usual Go rules), the following extra rules apply: -// -// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, -// even if there are multiple untagged fields that would otherwise conflict. -// 2) If there is exactly one field (tagged or not according to the first rule), that is selected. -// 3) Otherwise there are multiple fields, and all are ignored; no error occurs. -// -// Handling of anonymous struct fields is new in Go 1.1. -// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of -// an anonymous struct field in both current and earlier versions, give the field -// a JSON tag of "-". -// -// Map values encode as JSON objects. -// The map's key type must be string; the map keys are used as JSON object -// keys, subject to the UTF-8 coercion described for string values above. -// -// Pointer values encode as the value pointed to. -// A nil pointer encodes as the null JSON object. -// -// Interface values encode as the value contained in the interface. -// A nil interface value encodes as the null JSON object. -// -// Channel, complex, and function values cannot be encoded in JSON. -// Attempting to encode such a value causes Marshal to return -// an UnsupportedTypeError. -// -// JSON cannot represent cyclic data structures and Marshal does not -// handle them. Passing cyclic structures to Marshal will result in -// an infinite recursion. -// -func Marshal(v interface{}) ([]byte, error) { - e := &encodeState{} - err := e.marshal(v) - if err != nil { - return nil, err - } - return e.Bytes(), nil -} - -// MarshalIndent is like Marshal but applies Indent to format the output. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - b, err := Marshal(v) - if err != nil { - return nil, err - } - var buf bytes.Buffer - err = Indent(&buf, b, prefix, indent) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 -// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 -// so that the JSON will be safe to embed inside HTML + + diff --git a/vendor/nhooyr.io/websocket/examples/chat/index.js b/vendor/nhooyr.io/websocket/examples/chat/index.js new file mode 100644 index 0000000..5868e7c --- /dev/null +++ b/vendor/nhooyr.io/websocket/examples/chat/index.js @@ -0,0 +1,76 @@ +;(() => { + // expectingMessage is set to true + // if the user has just submitted a message + // and so we should scroll the next message into view when received. + let expectingMessage = false + function dial() { + const conn = new WebSocket(`ws://${location.host}/subscribe`) + + conn.addEventListener("close", ev => { + appendLog(`WebSocket Disconnected code: ${ev.code}, reason: ${ev.reason}`, true) + if (ev.code !== 1001) { + appendLog("Reconnecting in 1s", true) + setTimeout(dial, 1000) + } + }) + conn.addEventListener("open", ev => { + console.info("websocket connected") + }) + + // This is where we handle messages received. + conn.addEventListener("message", ev => { + if (typeof ev.data !== "string") { + console.error("unexpected message type", typeof ev.data) + return + } + const p = appendLog(ev.data) + if (expectingMessage) { + p.scrollIntoView() + expectingMessage = false + } + }) + } + dial() + + const messageLog = document.getElementById("message-log") + const publishForm = document.getElementById("publish-form") + const messageInput = document.getElementById("message-input") + + // appendLog appends the passed text to messageLog. + function appendLog(text, error) { + const p = document.createElement("p") + // Adding a timestamp to each message makes the log easier to read. + p.innerText = `${new Date().toLocaleTimeString()}: ${text}` + if (error) { + p.style.color = "red" + p.style.fontStyle = "bold" + } + messageLog.append(p) + return p + } + appendLog("Submit a message to get started!") + + // onsubmit publishes the message from the user when the form is submitted. + publishForm.onsubmit = async ev => { + ev.preventDefault() + + const msg = messageInput.value + if (msg === "") { + return + } + messageInput.value = "" + + expectingMessage = true + try { + const resp = await fetch("/publish", { + method: "POST", + body: msg, + }) + if (resp.status !== 202) { + throw new Error(`Unexpected HTTP Status ${resp.status} ${resp.statusText}`) + } + } catch (err) { + appendLog(`Publish failed: ${err.message}`, true) + } + } +})() diff --git a/vendor/nhooyr.io/websocket/examples/chat/main.go b/vendor/nhooyr.io/websocket/examples/chat/main.go new file mode 100644 index 0000000..3fcec6b --- /dev/null +++ b/vendor/nhooyr.io/websocket/examples/chat/main.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "errors" + "log" + "net" + "net/http" + "os" + "os/signal" + "time" +) + +func main() { + log.SetFlags(0) + + err := run() + if err != nil { + log.Fatal(err) + } +} + +// run initializes the chatServer and then +// starts a http.Server for the passed in address. +func run() error { + if len(os.Args) < 2 { + return errors.New("please provide an address to listen on as the first argument") + } + + l, err := net.Listen("tcp", os.Args[1]) + if err != nil { + return err + } + log.Printf("listening on http://%v", l.Addr()) + + cs := newChatServer() + s := &http.Server{ + Handler: cs, + ReadTimeout: time.Second * 10, + WriteTimeout: time.Second * 10, + } + errc := make(chan error, 1) + go func() { + errc <- s.Serve(l) + }() + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, os.Interrupt) + select { + case err := <-errc: + log.Printf("failed to serve: %v", err) + case sig := <-sigs: + log.Printf("terminating: %v", sig) + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + return s.Shutdown(ctx) +} diff --git a/vendor/nhooyr.io/websocket/examples/echo/README.md b/vendor/nhooyr.io/websocket/examples/echo/README.md new file mode 100644 index 0000000..7f42c3c --- /dev/null +++ b/vendor/nhooyr.io/websocket/examples/echo/README.md @@ -0,0 +1,21 @@ +# Echo Example + +This directory contains a echo server example using nhooyr.io/websocket. + +```bash +$ cd examples/echo +$ go run . localhost:0 +listening on http://127.0.0.1:51055 +``` + +You can use a WebSocket client like https://github.com/hashrocket/ws to connect. All messages +written will be echoed back. + +## Structure + +The server is in `server.go` and is implemented as a `http.HandlerFunc` that accepts the WebSocket +and then reads all messages and writes them exactly as is back to the connection. + +`server_test.go` contains a small unit test to verify it works correctly. + +`main.go` brings it all together so that you can run it and play around with it. diff --git a/vendor/nhooyr.io/websocket/examples/echo/main.go b/vendor/nhooyr.io/websocket/examples/echo/main.go new file mode 100644 index 0000000..16d78a7 --- /dev/null +++ b/vendor/nhooyr.io/websocket/examples/echo/main.go @@ -0,0 +1,61 @@ +package main + +import ( + "context" + "errors" + "log" + "net" + "net/http" + "os" + "os/signal" + "time" +) + +func main() { + log.SetFlags(0) + + err := run() + if err != nil { + log.Fatal(err) + } +} + +// run starts a http.Server for the passed in address +// with all requests handled by echoServer. +func run() error { + if len(os.Args) < 2 { + return errors.New("please provide an address to listen on as the first argument") + } + + l, err := net.Listen("tcp", os.Args[1]) + if err != nil { + return err + } + log.Printf("listening on http://%v", l.Addr()) + + s := &http.Server{ + Handler: echoServer{ + logf: log.Printf, + }, + ReadTimeout: time.Second * 10, + WriteTimeout: time.Second * 10, + } + errc := make(chan error, 1) + go func() { + errc <- s.Serve(l) + }() + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, os.Interrupt) + select { + case err := <-errc: + log.Printf("failed to serve: %v", err) + case sig := <-sigs: + log.Printf("terminating: %v", sig) + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + return s.Shutdown(ctx) +} diff --git a/vendor/nhooyr.io/websocket/examples/echo/server.go b/vendor/nhooyr.io/websocket/examples/echo/server.go new file mode 100644 index 0000000..e9f70f0 --- /dev/null +++ b/vendor/nhooyr.io/websocket/examples/echo/server.go @@ -0,0 +1,80 @@ +package main + +import ( + "context" + "fmt" + "io" + "net/http" + "time" + + "golang.org/x/time/rate" + + "nhooyr.io/websocket" +) + +// echoServer is the WebSocket echo server implementation. +// It ensures the client speaks the echo subprotocol and +// only allows one message every 100ms with a 10 message burst. +type echoServer struct { + // logf controls where logs are sent. + logf func(f string, v ...interface{}) +} + +func (s echoServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { + c, err := websocket.Accept(w, r, &websocket.AcceptOptions{ + Subprotocols: []string{"echo"}, + }) + if err != nil { + s.logf("%v", err) + return + } + defer c.Close(websocket.StatusInternalError, "the sky is falling") + + if c.Subprotocol() != "echo" { + c.Close(websocket.StatusPolicyViolation, "client must speak the echo subprotocol") + return + } + + l := rate.NewLimiter(rate.Every(time.Millisecond*100), 10) + for { + err = echo(r.Context(), c, l) + if websocket.CloseStatus(err) == websocket.StatusNormalClosure { + return + } + if err != nil { + s.logf("failed to echo with %v: %v", r.RemoteAddr, err) + return + } + } +} + +// echo reads from the WebSocket connection and then writes +// the received message back to it. +// The entire function has 10s to complete. +func echo(ctx context.Context, c *websocket.Conn, l *rate.Limiter) error { + ctx, cancel := context.WithTimeout(ctx, time.Second*10) + defer cancel() + + err := l.Wait(ctx) + if err != nil { + return err + } + + typ, r, err := c.Reader(ctx) + if err != nil { + return err + } + + w, err := c.Writer(ctx, typ) + if err != nil { + return err + } + + _, err = io.Copy(w, r) + if err != nil { + return fmt.Errorf("failed to io.Copy: %w", err) + } + + err = w.Close() + return err +} diff --git a/vendor/nhooyr.io/websocket/examples/echo/server_test.go b/vendor/nhooyr.io/websocket/examples/echo/server_test.go new file mode 100644 index 0000000..9b60830 --- /dev/null +++ b/vendor/nhooyr.io/websocket/examples/echo/server_test.go @@ -0,0 +1,54 @@ +package main + +import ( + "context" + "net/http/httptest" + "testing" + "time" + + "nhooyr.io/websocket" + "nhooyr.io/websocket/wsjson" +) + +// Test_echoServer tests the echoServer by sending it 5 different messages +// and ensuring the responses all match. +func Test_echoServer(t *testing.T) { + t.Parallel() + + s := httptest.NewServer(echoServer{ + logf: t.Logf, + }) + defer s.Close() + + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + + c, _, err := websocket.Dial(ctx, s.URL, &websocket.DialOptions{ + Subprotocols: []string{"echo"}, + }) + if err != nil { + t.Fatal(err) + } + defer c.Close(websocket.StatusInternalError, "the sky is falling") + + for i := 0; i < 5; i++ { + err = wsjson.Write(ctx, c, map[string]int{ + "i": i, + }) + if err != nil { + t.Fatal(err) + } + + v := map[string]int{} + err = wsjson.Read(ctx, c, &v) + if err != nil { + t.Fatal(err) + } + + if v["i"] != i { + t.Fatalf("expected %v but got %v", i, v) + } + } + + c.Close(websocket.StatusNormalClosure, "") +} diff --git a/vendor/nhooyr.io/websocket/export_test.go b/vendor/nhooyr.io/websocket/export_test.go new file mode 100644 index 0000000..88b82c9 --- /dev/null +++ b/vendor/nhooyr.io/websocket/export_test.go @@ -0,0 +1,22 @@ +// +build !js + +package websocket + +func (c *Conn) RecordBytesWritten() *int { + var bytesWritten int + c.bw.Reset(writerFunc(func(p []byte) (int, error) { + bytesWritten += len(p) + return c.rwc.Write(p) + })) + return &bytesWritten +} + +func (c *Conn) RecordBytesRead() *int { + var bytesRead int + c.br.Reset(readerFunc(func(p []byte) (int, error) { + n, err := c.rwc.Read(p) + bytesRead += n + return n, err + })) + return &bytesRead +} diff --git a/vendor/nhooyr.io/websocket/frame.go b/vendor/nhooyr.io/websocket/frame.go new file mode 100644 index 0000000..2a036f9 --- /dev/null +++ b/vendor/nhooyr.io/websocket/frame.go @@ -0,0 +1,294 @@ +package websocket + +import ( + "bufio" + "encoding/binary" + "fmt" + "io" + "math" + "math/bits" + + "nhooyr.io/websocket/internal/errd" +) + +// opcode represents a WebSocket opcode. +type opcode int + +// https://tools.ietf.org/html/rfc6455#section-11.8. +const ( + opContinuation opcode = iota + opText + opBinary + // 3 - 7 are reserved for further non-control frames. + _ + _ + _ + _ + _ + opClose + opPing + opPong + // 11-16 are reserved for further control frames. +) + +// header represents a WebSocket frame header. +// See https://tools.ietf.org/html/rfc6455#section-5.2. +type header struct { + fin bool + rsv1 bool + rsv2 bool + rsv3 bool + opcode opcode + + payloadLength int64 + + masked bool + maskKey uint32 +} + +// readFrameHeader reads a header from the reader. +// See https://tools.ietf.org/html/rfc6455#section-5.2. +func readFrameHeader(r *bufio.Reader, readBuf []byte) (h header, err error) { + defer errd.Wrap(&err, "failed to read frame header") + + b, err := r.ReadByte() + if err != nil { + return header{}, err + } + + h.fin = b&(1<<7) != 0 + h.rsv1 = b&(1<<6) != 0 + h.rsv2 = b&(1<<5) != 0 + h.rsv3 = b&(1<<4) != 0 + + h.opcode = opcode(b & 0xf) + + b, err = r.ReadByte() + if err != nil { + return header{}, err + } + + h.masked = b&(1<<7) != 0 + + payloadLength := b &^ (1 << 7) + switch { + case payloadLength < 126: + h.payloadLength = int64(payloadLength) + case payloadLength == 126: + _, err = io.ReadFull(r, readBuf[:2]) + h.payloadLength = int64(binary.BigEndian.Uint16(readBuf)) + case payloadLength == 127: + _, err = io.ReadFull(r, readBuf) + h.payloadLength = int64(binary.BigEndian.Uint64(readBuf)) + } + if err != nil { + return header{}, err + } + + if h.payloadLength < 0 { + return header{}, fmt.Errorf("received negative payload length: %v", h.payloadLength) + } + + if h.masked { + _, err = io.ReadFull(r, readBuf[:4]) + if err != nil { + return header{}, err + } + h.maskKey = binary.LittleEndian.Uint32(readBuf) + } + + return h, nil +} + +// maxControlPayload is the maximum length of a control frame payload. +// See https://tools.ietf.org/html/rfc6455#section-5.5. +const maxControlPayload = 125 + +// writeFrameHeader writes the bytes of the header to w. +// See https://tools.ietf.org/html/rfc6455#section-5.2 +func writeFrameHeader(h header, w *bufio.Writer, buf []byte) (err error) { + defer errd.Wrap(&err, "failed to write frame header") + + var b byte + if h.fin { + b |= 1 << 7 + } + if h.rsv1 { + b |= 1 << 6 + } + if h.rsv2 { + b |= 1 << 5 + } + if h.rsv3 { + b |= 1 << 4 + } + + b |= byte(h.opcode) + + err = w.WriteByte(b) + if err != nil { + return err + } + + lengthByte := byte(0) + if h.masked { + lengthByte |= 1 << 7 + } + + switch { + case h.payloadLength > math.MaxUint16: + lengthByte |= 127 + case h.payloadLength > 125: + lengthByte |= 126 + case h.payloadLength >= 0: + lengthByte |= byte(h.payloadLength) + } + err = w.WriteByte(lengthByte) + if err != nil { + return err + } + + switch { + case h.payloadLength > math.MaxUint16: + binary.BigEndian.PutUint64(buf, uint64(h.payloadLength)) + _, err = w.Write(buf) + case h.payloadLength > 125: + binary.BigEndian.PutUint16(buf, uint16(h.payloadLength)) + _, err = w.Write(buf[:2]) + } + if err != nil { + return err + } + + if h.masked { + binary.LittleEndian.PutUint32(buf, h.maskKey) + _, err = w.Write(buf[:4]) + if err != nil { + return err + } + } + + return nil +} + +// mask applies the WebSocket masking algorithm to p +// with the given key. +// See https://tools.ietf.org/html/rfc6455#section-5.3 +// +// The returned value is the correctly rotated key to +// to continue to mask/unmask the message. +// +// It is optimized for LittleEndian and expects the key +// to be in little endian. +// +// See https://github.com/golang/go/issues/31586 +func mask(key uint32, b []byte) uint32 { + if len(b) >= 8 { + key64 := uint64(key)<<32 | uint64(key) + + // At some point in the future we can clean these unrolled loops up. + // See https://github.com/golang/go/issues/31586#issuecomment-487436401 + + // Then we xor until b is less than 128 bytes. + for len(b) >= 128 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + v = binary.LittleEndian.Uint64(b[16:24]) + binary.LittleEndian.PutUint64(b[16:24], v^key64) + v = binary.LittleEndian.Uint64(b[24:32]) + binary.LittleEndian.PutUint64(b[24:32], v^key64) + v = binary.LittleEndian.Uint64(b[32:40]) + binary.LittleEndian.PutUint64(b[32:40], v^key64) + v = binary.LittleEndian.Uint64(b[40:48]) + binary.LittleEndian.PutUint64(b[40:48], v^key64) + v = binary.LittleEndian.Uint64(b[48:56]) + binary.LittleEndian.PutUint64(b[48:56], v^key64) + v = binary.LittleEndian.Uint64(b[56:64]) + binary.LittleEndian.PutUint64(b[56:64], v^key64) + v = binary.LittleEndian.Uint64(b[64:72]) + binary.LittleEndian.PutUint64(b[64:72], v^key64) + v = binary.LittleEndian.Uint64(b[72:80]) + binary.LittleEndian.PutUint64(b[72:80], v^key64) + v = binary.LittleEndian.Uint64(b[80:88]) + binary.LittleEndian.PutUint64(b[80:88], v^key64) + v = binary.LittleEndian.Uint64(b[88:96]) + binary.LittleEndian.PutUint64(b[88:96], v^key64) + v = binary.LittleEndian.Uint64(b[96:104]) + binary.LittleEndian.PutUint64(b[96:104], v^key64) + v = binary.LittleEndian.Uint64(b[104:112]) + binary.LittleEndian.PutUint64(b[104:112], v^key64) + v = binary.LittleEndian.Uint64(b[112:120]) + binary.LittleEndian.PutUint64(b[112:120], v^key64) + v = binary.LittleEndian.Uint64(b[120:128]) + binary.LittleEndian.PutUint64(b[120:128], v^key64) + b = b[128:] + } + + // Then we xor until b is less than 64 bytes. + for len(b) >= 64 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + v = binary.LittleEndian.Uint64(b[16:24]) + binary.LittleEndian.PutUint64(b[16:24], v^key64) + v = binary.LittleEndian.Uint64(b[24:32]) + binary.LittleEndian.PutUint64(b[24:32], v^key64) + v = binary.LittleEndian.Uint64(b[32:40]) + binary.LittleEndian.PutUint64(b[32:40], v^key64) + v = binary.LittleEndian.Uint64(b[40:48]) + binary.LittleEndian.PutUint64(b[40:48], v^key64) + v = binary.LittleEndian.Uint64(b[48:56]) + binary.LittleEndian.PutUint64(b[48:56], v^key64) + v = binary.LittleEndian.Uint64(b[56:64]) + binary.LittleEndian.PutUint64(b[56:64], v^key64) + b = b[64:] + } + + // Then we xor until b is less than 32 bytes. + for len(b) >= 32 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + v = binary.LittleEndian.Uint64(b[16:24]) + binary.LittleEndian.PutUint64(b[16:24], v^key64) + v = binary.LittleEndian.Uint64(b[24:32]) + binary.LittleEndian.PutUint64(b[24:32], v^key64) + b = b[32:] + } + + // Then we xor until b is less than 16 bytes. + for len(b) >= 16 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + b = b[16:] + } + + // Then we xor until b is less than 8 bytes. + for len(b) >= 8 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + b = b[8:] + } + } + + // Then we xor until b is less than 4 bytes. + for len(b) >= 4 { + v := binary.LittleEndian.Uint32(b) + binary.LittleEndian.PutUint32(b, v^key) + b = b[4:] + } + + // xor remaining bytes. + for i := range b { + b[i] ^= byte(key) + key = bits.RotateLeft32(key, -8) + } + + return key +} diff --git a/vendor/nhooyr.io/websocket/frame_test.go b/vendor/nhooyr.io/websocket/frame_test.go new file mode 100644 index 0000000..7682624 --- /dev/null +++ b/vendor/nhooyr.io/websocket/frame_test.go @@ -0,0 +1,192 @@ +// +build !js + +package websocket + +import ( + "bufio" + "bytes" + "encoding/binary" + "math/bits" + "math/rand" + "strconv" + "testing" + "time" + _ "unsafe" + + "github.com/gobwas/ws" + _ "github.com/gorilla/websocket" + + "nhooyr.io/websocket/internal/test/assert" +) + +func TestHeader(t *testing.T) { + t.Parallel() + + t.Run("lengths", func(t *testing.T) { + t.Parallel() + + lengths := []int{ + 124, + 125, + 126, + 127, + + 65534, + 65535, + 65536, + 65537, + } + + for _, n := range lengths { + n := n + t.Run(strconv.Itoa(n), func(t *testing.T) { + t.Parallel() + + testHeader(t, header{ + payloadLength: int64(n), + }) + }) + } + }) + + t.Run("fuzz", func(t *testing.T) { + t.Parallel() + + r := rand.New(rand.NewSource(time.Now().UnixNano())) + randBool := func() bool { + return r.Intn(1) == 0 + } + + for i := 0; i < 10000; i++ { + h := header{ + fin: randBool(), + rsv1: randBool(), + rsv2: randBool(), + rsv3: randBool(), + opcode: opcode(r.Intn(16)), + + masked: randBool(), + maskKey: r.Uint32(), + payloadLength: r.Int63(), + } + + testHeader(t, h) + } + }) +} + +func testHeader(t *testing.T, h header) { + b := &bytes.Buffer{} + w := bufio.NewWriter(b) + r := bufio.NewReader(b) + + err := writeFrameHeader(h, w, make([]byte, 8)) + assert.Success(t, err) + + err = w.Flush() + assert.Success(t, err) + + h2, err := readFrameHeader(r, make([]byte, 8)) + assert.Success(t, err) + + assert.Equal(t, "read header", h, h2) +} + +func Test_mask(t *testing.T) { + t.Parallel() + + key := []byte{0xa, 0xb, 0xc, 0xff} + key32 := binary.LittleEndian.Uint32(key) + p := []byte{0xa, 0xb, 0xc, 0xf2, 0xc} + gotKey32 := mask(key32, p) + + expP := []byte{0, 0, 0, 0x0d, 0x6} + assert.Equal(t, "p", expP, p) + + expKey32 := bits.RotateLeft32(key32, -8) + assert.Equal(t, "key32", expKey32, gotKey32) +} + +func basicMask(maskKey [4]byte, pos int, b []byte) int { + for i := range b { + b[i] ^= maskKey[pos&3] + pos++ + } + return pos & 3 +} + +//go:linkname gorillaMaskBytes github.com/gorilla/websocket.maskBytes +func gorillaMaskBytes(key [4]byte, pos int, b []byte) int + +func Benchmark_mask(b *testing.B) { + sizes := []int{ + 2, + 3, + 4, + 8, + 16, + 32, + 128, + 512, + 4096, + 16384, + } + + fns := []struct { + name string + fn func(b *testing.B, key [4]byte, p []byte) + }{ + { + name: "basic", + fn: func(b *testing.B, key [4]byte, p []byte) { + for i := 0; i < b.N; i++ { + basicMask(key, 0, p) + } + }, + }, + + { + name: "nhooyr", + fn: func(b *testing.B, key [4]byte, p []byte) { + key32 := binary.LittleEndian.Uint32(key[:]) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + mask(key32, p) + } + }, + }, + { + name: "gorilla", + fn: func(b *testing.B, key [4]byte, p []byte) { + for i := 0; i < b.N; i++ { + gorillaMaskBytes(key, 0, p) + } + }, + }, + { + name: "gobwas", + fn: func(b *testing.B, key [4]byte, p []byte) { + for i := 0; i < b.N; i++ { + ws.Cipher(p, key, 0) + } + }, + }, + } + + key := [4]byte{1, 2, 3, 4} + + for _, size := range sizes { + p := make([]byte, size) + + b.Run(strconv.Itoa(size), func(b *testing.B) { + for _, fn := range fns { + b.Run(fn.name, func(b *testing.B) { + b.SetBytes(int64(size)) + + fn.fn(b, key, p) + }) + } + }) + } +} diff --git a/vendor/nhooyr.io/websocket/go.mod b/vendor/nhooyr.io/websocket/go.mod new file mode 100644 index 0000000..c5f1a20 --- /dev/null +++ b/vendor/nhooyr.io/websocket/go.mod @@ -0,0 +1,15 @@ +module nhooyr.io/websocket + +go 1.13 + +require ( + github.com/gin-gonic/gin v1.6.3 + github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee // indirect + github.com/gobwas/pool v0.2.0 // indirect + github.com/gobwas/ws v1.0.2 + github.com/golang/protobuf v1.3.5 + github.com/google/go-cmp v0.4.0 + github.com/gorilla/websocket v1.4.1 + github.com/klauspost/compress v1.10.3 + golang.org/x/time v0.0.0-20191024005414-555d28b269f0 +) diff --git a/vendor/nhooyr.io/websocket/go.sum b/vendor/nhooyr.io/websocket/go.sum new file mode 100644 index 0000000..155c301 --- /dev/null +++ b/vendor/nhooyr.io/websocket/go.sum @@ -0,0 +1,64 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= +github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= +github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5 h1:F768QJ1E9tib+q5Sc8MkdJi1RxLTbRcTf8LJV56aRls= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/klauspost/compress v1.10.3 h1:OP96hzwJVBIHYU52pVTI6CczrxPvrGfgqF9N5eTO0Q8= +github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/nhooyr.io/websocket/internal/bpool/bpool.go b/vendor/nhooyr.io/websocket/internal/bpool/bpool.go new file mode 100644 index 0000000..aa826fb --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/bpool/bpool.go @@ -0,0 +1,24 @@ +package bpool + +import ( + "bytes" + "sync" +) + +var bpool sync.Pool + +// Get returns a buffer from the pool or creates a new one if +// the pool is empty. +func Get() *bytes.Buffer { + b := bpool.Get() + if b == nil { + return &bytes.Buffer{} + } + return b.(*bytes.Buffer) +} + +// Put returns a buffer into the pool. +func Put(b *bytes.Buffer) { + b.Reset() + bpool.Put(b) +} diff --git a/vendor/nhooyr.io/websocket/internal/errd/wrap.go b/vendor/nhooyr.io/websocket/internal/errd/wrap.go new file mode 100644 index 0000000..6e77913 --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/errd/wrap.go @@ -0,0 +1,14 @@ +package errd + +import ( + "fmt" +) + +// Wrap wraps err with fmt.Errorf if err is non nil. +// Intended for use with defer and a named error return. +// Inspired by https://github.com/golang/go/issues/32676. +func Wrap(err *error, f string, v ...interface{}) { + if *err != nil { + *err = fmt.Errorf(f+": %w", append(v, *err)...) + } +} diff --git a/vendor/nhooyr.io/websocket/internal/test/assert/assert.go b/vendor/nhooyr.io/websocket/internal/test/assert/assert.go new file mode 100644 index 0000000..6eaf7fc --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/test/assert/assert.go @@ -0,0 +1,56 @@ +package assert + +import ( + "fmt" + "reflect" + "strings" + "testing" + + "github.com/golang/protobuf/proto" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" +) + +// Diff returns a human readable diff between v1 and v2 +func Diff(v1, v2 interface{}) string { + return cmp.Diff(v1, v2, cmpopts.EquateErrors(), cmp.Exporter(func(r reflect.Type) bool { + return true + }), cmp.Comparer(proto.Equal)) +} + +// Equal asserts exp == act. +func Equal(t testing.TB, name string, exp, act interface{}) { + t.Helper() + + if diff := Diff(exp, act); diff != "" { + t.Fatalf("unexpected %v: %v", name, diff) + } +} + +// Success asserts err == nil. +func Success(t testing.TB, err error) { + t.Helper() + + if err != nil { + t.Fatal(err) + } +} + +// Error asserts err != nil. +func Error(t testing.TB, err error) { + t.Helper() + + if err == nil { + t.Fatal("expected error") + } +} + +// Contains asserts the fmt.Sprint(v) contains sub. +func Contains(t testing.TB, v interface{}, sub string) { + t.Helper() + + s := fmt.Sprint(v) + if !strings.Contains(s, sub) { + t.Fatalf("expected %q to contain %q", s, sub) + } +} diff --git a/vendor/nhooyr.io/websocket/internal/test/doc.go b/vendor/nhooyr.io/websocket/internal/test/doc.go new file mode 100644 index 0000000..94b2e82 --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/test/doc.go @@ -0,0 +1,2 @@ +// Package test contains subpackages only used in tests. +package test diff --git a/vendor/nhooyr.io/websocket/internal/test/wstest/echo.go b/vendor/nhooyr.io/websocket/internal/test/wstest/echo.go new file mode 100644 index 0000000..8f4e47c --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/test/wstest/echo.go @@ -0,0 +1,90 @@ +package wstest + +import ( + "bytes" + "context" + "fmt" + "io" + "time" + + "nhooyr.io/websocket" + "nhooyr.io/websocket/internal/test/assert" + "nhooyr.io/websocket/internal/test/xrand" + "nhooyr.io/websocket/internal/xsync" +) + +// EchoLoop echos every msg received from c until an error +// occurs or the context expires. +// The read limit is set to 1 << 30. +func EchoLoop(ctx context.Context, c *websocket.Conn) error { + defer c.Close(websocket.StatusInternalError, "") + + c.SetReadLimit(1 << 30) + + ctx, cancel := context.WithTimeout(ctx, time.Minute) + defer cancel() + + b := make([]byte, 32<<10) + for { + typ, r, err := c.Reader(ctx) + if err != nil { + return err + } + + w, err := c.Writer(ctx, typ) + if err != nil { + return err + } + + _, err = io.CopyBuffer(w, r, b) + if err != nil { + return err + } + + err = w.Close() + if err != nil { + return err + } + } +} + +// Echo writes a message and ensures the same is sent back on c. +func Echo(ctx context.Context, c *websocket.Conn, max int) error { + expType := websocket.MessageBinary + if xrand.Bool() { + expType = websocket.MessageText + } + + msg := randMessage(expType, xrand.Int(max)) + + writeErr := xsync.Go(func() error { + return c.Write(ctx, expType, msg) + }) + + actType, act, err := c.Read(ctx) + if err != nil { + return err + } + + err = <-writeErr + if err != nil { + return err + } + + if expType != actType { + return fmt.Errorf("unexpected message typ (%v): %v", expType, actType) + } + + if !bytes.Equal(msg, act) { + return fmt.Errorf("unexpected msg read: %v", assert.Diff(msg, act)) + } + + return nil +} + +func randMessage(typ websocket.MessageType, n int) []byte { + if typ == websocket.MessageBinary { + return xrand.Bytes(n) + } + return []byte(xrand.String(n)) +} diff --git a/vendor/nhooyr.io/websocket/internal/test/wstest/pipe.go b/vendor/nhooyr.io/websocket/internal/test/wstest/pipe.go new file mode 100644 index 0000000..1534f31 --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/test/wstest/pipe.go @@ -0,0 +1,66 @@ +// +build !js + +package wstest + +import ( + "bufio" + "context" + "net" + "net/http" + "net/http/httptest" + + "nhooyr.io/websocket" +) + +// Pipe is used to create an in memory connection +// between two websockets analogous to net.Pipe. +func Pipe(dialOpts *websocket.DialOptions, acceptOpts *websocket.AcceptOptions) (clientConn, serverConn *websocket.Conn) { + tt := fakeTransport{ + h: func(w http.ResponseWriter, r *http.Request) { + serverConn, _ = websocket.Accept(w, r, acceptOpts) + }, + } + + if dialOpts == nil { + dialOpts = &websocket.DialOptions{} + } + dialOpts = &*dialOpts + dialOpts.HTTPClient = &http.Client{ + Transport: tt, + } + + clientConn, _, _ = websocket.Dial(context.Background(), "ws://example.com", dialOpts) + return clientConn, serverConn +} + +type fakeTransport struct { + h http.HandlerFunc +} + +func (t fakeTransport) RoundTrip(r *http.Request) (*http.Response, error) { + clientConn, serverConn := net.Pipe() + + hj := testHijacker{ + ResponseRecorder: httptest.NewRecorder(), + serverConn: serverConn, + } + + t.h.ServeHTTP(hj, r) + + resp := hj.ResponseRecorder.Result() + if resp.StatusCode == http.StatusSwitchingProtocols { + resp.Body = clientConn + } + return resp, nil +} + +type testHijacker struct { + *httptest.ResponseRecorder + serverConn net.Conn +} + +var _ http.Hijacker = testHijacker{} + +func (hj testHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return hj.serverConn, bufio.NewReadWriter(bufio.NewReader(hj.serverConn), bufio.NewWriter(hj.serverConn)), nil +} diff --git a/vendor/nhooyr.io/websocket/internal/test/xrand/xrand.go b/vendor/nhooyr.io/websocket/internal/test/xrand/xrand.go new file mode 100644 index 0000000..8de1ede --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/test/xrand/xrand.go @@ -0,0 +1,47 @@ +package xrand + +import ( + "crypto/rand" + "fmt" + "math/big" + "strings" +) + +// Bytes generates random bytes with length n. +func Bytes(n int) []byte { + b := make([]byte, n) + _, err := rand.Reader.Read(b) + if err != nil { + panic(fmt.Sprintf("failed to generate rand bytes: %v", err)) + } + return b +} + +// String generates a random string with length n. +func String(n int) string { + s := strings.ToValidUTF8(string(Bytes(n)), "_") + s = strings.ReplaceAll(s, "\x00", "_") + if len(s) > n { + return s[:n] + } + if len(s) < n { + // Pad with = + extra := n - len(s) + return s + strings.Repeat("=", extra) + } + return s +} + +// Bool returns a randomly generated boolean. +func Bool() bool { + return Int(2) == 1 +} + +// Int returns a randomly generated integer between [0, max). +func Int(max int) int { + x, err := rand.Int(rand.Reader, big.NewInt(int64(max))) + if err != nil { + panic(fmt.Sprintf("failed to get random int: %v", err)) + } + return int(x.Int64()) +} diff --git a/vendor/nhooyr.io/websocket/internal/wsjs/wsjs_js.go b/vendor/nhooyr.io/websocket/internal/wsjs/wsjs_js.go new file mode 100644 index 0000000..26ffb45 --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/wsjs/wsjs_js.go @@ -0,0 +1,170 @@ +// +build js + +// Package wsjs implements typed access to the browser javascript WebSocket API. +// +// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket +package wsjs + +import ( + "syscall/js" +) + +func handleJSError(err *error, onErr func()) { + r := recover() + + if jsErr, ok := r.(js.Error); ok { + *err = jsErr + + if onErr != nil { + onErr() + } + return + } + + if r != nil { + panic(r) + } +} + +// New is a wrapper around the javascript WebSocket constructor. +func New(url string, protocols []string) (c WebSocket, err error) { + defer handleJSError(&err, func() { + c = WebSocket{} + }) + + jsProtocols := make([]interface{}, len(protocols)) + for i, p := range protocols { + jsProtocols[i] = p + } + + c = WebSocket{ + v: js.Global().Get("WebSocket").New(url, jsProtocols), + } + + c.setBinaryType("arraybuffer") + + return c, nil +} + +// WebSocket is a wrapper around a javascript WebSocket object. +type WebSocket struct { + v js.Value +} + +func (c WebSocket) setBinaryType(typ string) { + c.v.Set("binaryType", string(typ)) +} + +func (c WebSocket) addEventListener(eventType string, fn func(e js.Value)) func() { + f := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + fn(args[0]) + return nil + }) + c.v.Call("addEventListener", eventType, f) + + return func() { + c.v.Call("removeEventListener", eventType, f) + f.Release() + } +} + +// CloseEvent is the type passed to a WebSocket close handler. +type CloseEvent struct { + Code uint16 + Reason string + WasClean bool +} + +// OnClose registers a function to be called when the WebSocket is closed. +func (c WebSocket) OnClose(fn func(CloseEvent)) (remove func()) { + return c.addEventListener("close", func(e js.Value) { + ce := CloseEvent{ + Code: uint16(e.Get("code").Int()), + Reason: e.Get("reason").String(), + WasClean: e.Get("wasClean").Bool(), + } + fn(ce) + }) +} + +// OnError registers a function to be called when there is an error +// with the WebSocket. +func (c WebSocket) OnError(fn func(e js.Value)) (remove func()) { + return c.addEventListener("error", fn) +} + +// MessageEvent is the type passed to a message handler. +type MessageEvent struct { + // string or []byte. + Data interface{} + + // There are more fields to the interface but we don't use them. + // See https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent +} + +// OnMessage registers a function to be called when the WebSocket receives a message. +func (c WebSocket) OnMessage(fn func(m MessageEvent)) (remove func()) { + return c.addEventListener("message", func(e js.Value) { + var data interface{} + + arrayBuffer := e.Get("data") + if arrayBuffer.Type() == js.TypeString { + data = arrayBuffer.String() + } else { + data = extractArrayBuffer(arrayBuffer) + } + + me := MessageEvent{ + Data: data, + } + fn(me) + + return + }) +} + +// Subprotocol returns the WebSocket subprotocol in use. +func (c WebSocket) Subprotocol() string { + return c.v.Get("protocol").String() +} + +// OnOpen registers a function to be called when the WebSocket is opened. +func (c WebSocket) OnOpen(fn func(e js.Value)) (remove func()) { + return c.addEventListener("open", fn) +} + +// Close closes the WebSocket with the given code and reason. +func (c WebSocket) Close(code int, reason string) (err error) { + defer handleJSError(&err, nil) + c.v.Call("close", code, reason) + return err +} + +// SendText sends the given string as a text message +// on the WebSocket. +func (c WebSocket) SendText(v string) (err error) { + defer handleJSError(&err, nil) + c.v.Call("send", v) + return err +} + +// SendBytes sends the given message as a binary message +// on the WebSocket. +func (c WebSocket) SendBytes(v []byte) (err error) { + defer handleJSError(&err, nil) + c.v.Call("send", uint8Array(v)) + return err +} + +func extractArrayBuffer(arrayBuffer js.Value) []byte { + uint8Array := js.Global().Get("Uint8Array").New(arrayBuffer) + dst := make([]byte, uint8Array.Length()) + js.CopyBytesToGo(dst, uint8Array) + return dst +} + +func uint8Array(src []byte) js.Value { + uint8Array := js.Global().Get("Uint8Array").New(len(src)) + js.CopyBytesToJS(uint8Array, src) + return uint8Array +} diff --git a/vendor/nhooyr.io/websocket/internal/xsync/go.go b/vendor/nhooyr.io/websocket/internal/xsync/go.go new file mode 100644 index 0000000..7a61f27 --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/xsync/go.go @@ -0,0 +1,25 @@ +package xsync + +import ( + "fmt" +) + +// Go allows running a function in another goroutine +// and waiting for its error. +func Go(fn func() error) <-chan error { + errs := make(chan error, 1) + go func() { + defer func() { + r := recover() + if r != nil { + select { + case errs <- fmt.Errorf("panic in go fn: %v", r): + default: + } + } + }() + errs <- fn() + }() + + return errs +} diff --git a/vendor/nhooyr.io/websocket/internal/xsync/go_test.go b/vendor/nhooyr.io/websocket/internal/xsync/go_test.go new file mode 100644 index 0000000..dabea8a --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/xsync/go_test.go @@ -0,0 +1,18 @@ +package xsync + +import ( + "testing" + + "nhooyr.io/websocket/internal/test/assert" +) + +func TestGoRecover(t *testing.T) { + t.Parallel() + + errs := Go(func() error { + panic("anmol") + }) + + err := <-errs + assert.Contains(t, err, "anmol") +} diff --git a/vendor/nhooyr.io/websocket/internal/xsync/int64.go b/vendor/nhooyr.io/websocket/internal/xsync/int64.go new file mode 100644 index 0000000..a0c4020 --- /dev/null +++ b/vendor/nhooyr.io/websocket/internal/xsync/int64.go @@ -0,0 +1,23 @@ +package xsync + +import ( + "sync/atomic" +) + +// Int64 represents an atomic int64. +type Int64 struct { + // We do not use atomic.Load/StoreInt64 since it does not + // work on 32 bit computers but we need 64 bit integers. + i atomic.Value +} + +// Load loads the int64. +func (v *Int64) Load() int64 { + i, _ := v.i.Load().(int64) + return i +} + +// Store stores the int64. +func (v *Int64) Store(i int64) { + v.i.Store(i) +} diff --git a/vendor/nhooyr.io/websocket/netconn.go b/vendor/nhooyr.io/websocket/netconn.go new file mode 100644 index 0000000..64aadf0 --- /dev/null +++ b/vendor/nhooyr.io/websocket/netconn.go @@ -0,0 +1,166 @@ +package websocket + +import ( + "context" + "fmt" + "io" + "math" + "net" + "sync" + "time" +) + +// NetConn converts a *websocket.Conn into a net.Conn. +// +// It's for tunneling arbitrary protocols over WebSockets. +// Few users of the library will need this but it's tricky to implement +// correctly and so provided in the library. +// See https://github.com/nhooyr/websocket/issues/100. +// +// Every Write to the net.Conn will correspond to a message write of +// the given type on *websocket.Conn. +// +// The passed ctx bounds the lifetime of the net.Conn. If cancelled, +// all reads and writes on the net.Conn will be cancelled. +// +// If a message is read that is not of the correct type, the connection +// will be closed with StatusUnsupportedData and an error will be returned. +// +// Close will close the *websocket.Conn with StatusNormalClosure. +// +// When a deadline is hit, the connection will be closed. This is +// different from most net.Conn implementations where only the +// reading/writing goroutines are interrupted but the connection is kept alive. +// +// The Addr methods will return a mock net.Addr that returns "websocket" for Network +// and "websocket/unknown-addr" for String. +// +// A received StatusNormalClosure or StatusGoingAway close frame will be translated to +// io.EOF when reading. +func NetConn(ctx context.Context, c *Conn, msgType MessageType) net.Conn { + nc := &netConn{ + c: c, + msgType: msgType, + } + + var cancel context.CancelFunc + nc.writeContext, cancel = context.WithCancel(ctx) + nc.writeTimer = time.AfterFunc(math.MaxInt64, cancel) + if !nc.writeTimer.Stop() { + <-nc.writeTimer.C + } + + nc.readContext, cancel = context.WithCancel(ctx) + nc.readTimer = time.AfterFunc(math.MaxInt64, cancel) + if !nc.readTimer.Stop() { + <-nc.readTimer.C + } + + return nc +} + +type netConn struct { + c *Conn + msgType MessageType + + writeTimer *time.Timer + writeContext context.Context + + readTimer *time.Timer + readContext context.Context + + readMu sync.Mutex + eofed bool + reader io.Reader +} + +var _ net.Conn = &netConn{} + +func (c *netConn) Close() error { + return c.c.Close(StatusNormalClosure, "") +} + +func (c *netConn) Write(p []byte) (int, error) { + err := c.c.Write(c.writeContext, c.msgType, p) + if err != nil { + return 0, err + } + return len(p), nil +} + +func (c *netConn) Read(p []byte) (int, error) { + c.readMu.Lock() + defer c.readMu.Unlock() + + if c.eofed { + return 0, io.EOF + } + + if c.reader == nil { + typ, r, err := c.c.Reader(c.readContext) + if err != nil { + switch CloseStatus(err) { + case StatusNormalClosure, StatusGoingAway: + c.eofed = true + return 0, io.EOF + } + return 0, err + } + if typ != c.msgType { + err := fmt.Errorf("unexpected frame type read (expected %v): %v", c.msgType, typ) + c.c.Close(StatusUnsupportedData, err.Error()) + return 0, err + } + c.reader = r + } + + n, err := c.reader.Read(p) + if err == io.EOF { + c.reader = nil + err = nil + } + return n, err +} + +type websocketAddr struct { +} + +func (a websocketAddr) Network() string { + return "websocket" +} + +func (a websocketAddr) String() string { + return "websocket/unknown-addr" +} + +func (c *netConn) RemoteAddr() net.Addr { + return websocketAddr{} +} + +func (c *netConn) LocalAddr() net.Addr { + return websocketAddr{} +} + +func (c *netConn) SetDeadline(t time.Time) error { + c.SetWriteDeadline(t) + c.SetReadDeadline(t) + return nil +} + +func (c *netConn) SetWriteDeadline(t time.Time) error { + if t.IsZero() { + c.writeTimer.Stop() + } else { + c.writeTimer.Reset(t.Sub(time.Now())) + } + return nil +} + +func (c *netConn) SetReadDeadline(t time.Time) error { + if t.IsZero() { + c.readTimer.Stop() + } else { + c.readTimer.Reset(t.Sub(time.Now())) + } + return nil +} diff --git a/vendor/nhooyr.io/websocket/read.go b/vendor/nhooyr.io/websocket/read.go new file mode 100644 index 0000000..afd08cc --- /dev/null +++ b/vendor/nhooyr.io/websocket/read.go @@ -0,0 +1,471 @@ +// +build !js + +package websocket + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "io/ioutil" + "strings" + "time" + + "nhooyr.io/websocket/internal/errd" + "nhooyr.io/websocket/internal/xsync" +) + +// Reader reads from the connection until until there is a WebSocket +// data message to be read. It will handle ping, pong and close frames as appropriate. +// +// It returns the type of the message and an io.Reader to read it. +// The passed context will also bound the reader. +// Ensure you read to EOF otherwise the connection will hang. +// +// Call CloseRead if you do not expect any data messages from the peer. +// +// Only one Reader may be open at a time. +func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error) { + return c.reader(ctx) +} + +// Read is a convenience method around Reader to read a single message +// from the connection. +func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error) { + typ, r, err := c.Reader(ctx) + if err != nil { + return 0, nil, err + } + + b, err := ioutil.ReadAll(r) + return typ, b, err +} + +// CloseRead starts a goroutine to read from the connection until it is closed +// or a data message is received. +// +// Once CloseRead is called you cannot read any messages from the connection. +// The returned context will be cancelled when the connection is closed. +// +// If a data message is received, the connection will be closed with StatusPolicyViolation. +// +// Call CloseRead when you do not expect to read any more messages. +// Since it actively reads from the connection, it will ensure that ping, pong and close +// frames are responded to. This means c.Ping and c.Close will still work as expected. +func (c *Conn) CloseRead(ctx context.Context) context.Context { + ctx, cancel := context.WithCancel(ctx) + go func() { + defer cancel() + c.Reader(ctx) + c.Close(StatusPolicyViolation, "unexpected data message") + }() + return ctx +} + +// SetReadLimit sets the max number of bytes to read for a single message. +// It applies to the Reader and Read methods. +// +// By default, the connection has a message read limit of 32768 bytes. +// +// When the limit is hit, the connection will be closed with StatusMessageTooBig. +func (c *Conn) SetReadLimit(n int64) { + // We add read one more byte than the limit in case + // there is a fin frame that needs to be read. + c.msgReader.limitReader.limit.Store(n + 1) +} + +const defaultReadLimit = 32768 + +func newMsgReader(c *Conn) *msgReader { + mr := &msgReader{ + c: c, + fin: true, + } + mr.readFunc = mr.read + + mr.limitReader = newLimitReader(c, mr.readFunc, defaultReadLimit+1) + return mr +} + +func (mr *msgReader) resetFlate() { + if mr.flateContextTakeover() { + mr.dict.init(32768) + } + if mr.flateBufio == nil { + mr.flateBufio = getBufioReader(mr.readFunc) + } + + mr.flateReader = getFlateReader(mr.flateBufio, mr.dict.buf) + mr.limitReader.r = mr.flateReader + mr.flateTail.Reset(deflateMessageTail) +} + +func (mr *msgReader) putFlateReader() { + if mr.flateReader != nil { + putFlateReader(mr.flateReader) + mr.flateReader = nil + } +} + +func (mr *msgReader) close() { + mr.c.readMu.forceLock() + mr.putFlateReader() + mr.dict.close() + if mr.flateBufio != nil { + putBufioReader(mr.flateBufio) + } + + if mr.c.client { + putBufioReader(mr.c.br) + mr.c.br = nil + } +} + +func (mr *msgReader) flateContextTakeover() bool { + if mr.c.client { + return !mr.c.copts.serverNoContextTakeover + } + return !mr.c.copts.clientNoContextTakeover +} + +func (c *Conn) readRSV1Illegal(h header) bool { + // If compression is disabled, rsv1 is illegal. + if !c.flate() { + return true + } + // rsv1 is only allowed on data frames beginning messages. + if h.opcode != opText && h.opcode != opBinary { + return true + } + return false +} + +func (c *Conn) readLoop(ctx context.Context) (header, error) { + for { + h, err := c.readFrameHeader(ctx) + if err != nil { + return header{}, err + } + + if h.rsv1 && c.readRSV1Illegal(h) || h.rsv2 || h.rsv3 { + err := fmt.Errorf("received header with unexpected rsv bits set: %v:%v:%v", h.rsv1, h.rsv2, h.rsv3) + c.writeError(StatusProtocolError, err) + return header{}, err + } + + if !c.client && !h.masked { + return header{}, errors.New("received unmasked frame from client") + } + + switch h.opcode { + case opClose, opPing, opPong: + err = c.handleControl(ctx, h) + if err != nil { + // Pass through CloseErrors when receiving a close frame. + if h.opcode == opClose && CloseStatus(err) != -1 { + return header{}, err + } + return header{}, fmt.Errorf("failed to handle control frame %v: %w", h.opcode, err) + } + case opContinuation, opText, opBinary: + return h, nil + default: + err := fmt.Errorf("received unknown opcode %v", h.opcode) + c.writeError(StatusProtocolError, err) + return header{}, err + } + } +} + +func (c *Conn) readFrameHeader(ctx context.Context) (header, error) { + select { + case <-c.closed: + return header{}, c.closeErr + case c.readTimeout <- ctx: + } + + h, err := readFrameHeader(c.br, c.readHeaderBuf[:]) + if err != nil { + select { + case <-c.closed: + return header{}, c.closeErr + case <-ctx.Done(): + return header{}, ctx.Err() + default: + c.close(err) + return header{}, err + } + } + + select { + case <-c.closed: + return header{}, c.closeErr + case c.readTimeout <- context.Background(): + } + + return h, nil +} + +func (c *Conn) readFramePayload(ctx context.Context, p []byte) (int, error) { + select { + case <-c.closed: + return 0, c.closeErr + case c.readTimeout <- ctx: + } + + n, err := io.ReadFull(c.br, p) + if err != nil { + select { + case <-c.closed: + return n, c.closeErr + case <-ctx.Done(): + return n, ctx.Err() + default: + err = fmt.Errorf("failed to read frame payload: %w", err) + c.close(err) + return n, err + } + } + + select { + case <-c.closed: + return n, c.closeErr + case c.readTimeout <- context.Background(): + } + + return n, err +} + +func (c *Conn) handleControl(ctx context.Context, h header) (err error) { + if h.payloadLength < 0 || h.payloadLength > maxControlPayload { + err := fmt.Errorf("received control frame payload with invalid length: %d", h.payloadLength) + c.writeError(StatusProtocolError, err) + return err + } + + if !h.fin { + err := errors.New("received fragmented control frame") + c.writeError(StatusProtocolError, err) + return err + } + + ctx, cancel := context.WithTimeout(ctx, time.Second*5) + defer cancel() + + b := c.readControlBuf[:h.payloadLength] + _, err = c.readFramePayload(ctx, b) + if err != nil { + return err + } + + if h.masked { + mask(h.maskKey, b) + } + + switch h.opcode { + case opPing: + return c.writeControl(ctx, opPong, b) + case opPong: + c.activePingsMu.Lock() + pong, ok := c.activePings[string(b)] + c.activePingsMu.Unlock() + if ok { + close(pong) + } + return nil + } + + defer func() { + c.readCloseFrameErr = err + }() + + ce, err := parseClosePayload(b) + if err != nil { + err = fmt.Errorf("received invalid close payload: %w", err) + c.writeError(StatusProtocolError, err) + return err + } + + err = fmt.Errorf("received close frame: %w", ce) + c.setCloseErr(err) + c.writeClose(ce.Code, ce.Reason) + c.close(err) + return err +} + +func (c *Conn) reader(ctx context.Context) (_ MessageType, _ io.Reader, err error) { + defer errd.Wrap(&err, "failed to get reader") + + err = c.readMu.lock(ctx) + if err != nil { + return 0, nil, err + } + defer c.readMu.unlock() + + if !c.msgReader.fin { + err = errors.New("previous message not read to completion") + c.close(fmt.Errorf("failed to get reader: %w", err)) + return 0, nil, err + } + + h, err := c.readLoop(ctx) + if err != nil { + return 0, nil, err + } + + if h.opcode == opContinuation { + err := errors.New("received continuation frame without text or binary frame") + c.writeError(StatusProtocolError, err) + return 0, nil, err + } + + c.msgReader.reset(ctx, h) + + return MessageType(h.opcode), c.msgReader, nil +} + +type msgReader struct { + c *Conn + + ctx context.Context + flate bool + flateReader io.Reader + flateBufio *bufio.Reader + flateTail strings.Reader + limitReader *limitReader + dict slidingWindow + + fin bool + payloadLength int64 + maskKey uint32 + + // readerFunc(mr.Read) to avoid continuous allocations. + readFunc readerFunc +} + +func (mr *msgReader) reset(ctx context.Context, h header) { + mr.ctx = ctx + mr.flate = h.rsv1 + mr.limitReader.reset(mr.readFunc) + + if mr.flate { + mr.resetFlate() + } + + mr.setFrame(h) +} + +func (mr *msgReader) setFrame(h header) { + mr.fin = h.fin + mr.payloadLength = h.payloadLength + mr.maskKey = h.maskKey +} + +func (mr *msgReader) Read(p []byte) (n int, err error) { + err = mr.c.readMu.lock(mr.ctx) + if err != nil { + return 0, fmt.Errorf("failed to read: %w", err) + } + defer mr.c.readMu.unlock() + + n, err = mr.limitReader.Read(p) + if mr.flate && mr.flateContextTakeover() { + p = p[:n] + mr.dict.write(p) + } + if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) && mr.fin && mr.flate { + mr.putFlateReader() + return n, io.EOF + } + if err != nil { + err = fmt.Errorf("failed to read: %w", err) + mr.c.close(err) + } + return n, err +} + +func (mr *msgReader) read(p []byte) (int, error) { + for { + if mr.payloadLength == 0 { + if mr.fin { + if mr.flate { + return mr.flateTail.Read(p) + } + return 0, io.EOF + } + + h, err := mr.c.readLoop(mr.ctx) + if err != nil { + return 0, err + } + if h.opcode != opContinuation { + err := errors.New("received new data message without finishing the previous message") + mr.c.writeError(StatusProtocolError, err) + return 0, err + } + mr.setFrame(h) + + continue + } + + if int64(len(p)) > mr.payloadLength { + p = p[:mr.payloadLength] + } + + n, err := mr.c.readFramePayload(mr.ctx, p) + if err != nil { + return n, err + } + + mr.payloadLength -= int64(n) + + if !mr.c.client { + mr.maskKey = mask(mr.maskKey, p) + } + + return n, nil + } +} + +type limitReader struct { + c *Conn + r io.Reader + limit xsync.Int64 + n int64 +} + +func newLimitReader(c *Conn, r io.Reader, limit int64) *limitReader { + lr := &limitReader{ + c: c, + } + lr.limit.Store(limit) + lr.reset(r) + return lr +} + +func (lr *limitReader) reset(r io.Reader) { + lr.n = lr.limit.Load() + lr.r = r +} + +func (lr *limitReader) Read(p []byte) (int, error) { + if lr.n <= 0 { + err := fmt.Errorf("read limited at %v bytes", lr.limit.Load()) + lr.c.writeError(StatusMessageTooBig, err) + return 0, err + } + + if int64(len(p)) > lr.n { + p = p[:lr.n] + } + n, err := lr.r.Read(p) + lr.n -= int64(n) + return n, err +} + +type readerFunc func(p []byte) (int, error) + +func (f readerFunc) Read(p []byte) (int, error) { + return f(p) +} diff --git a/vendor/nhooyr.io/websocket/stringer.go b/vendor/nhooyr.io/websocket/stringer.go new file mode 100644 index 0000000..5a66ba2 --- /dev/null +++ b/vendor/nhooyr.io/websocket/stringer.go @@ -0,0 +1,91 @@ +// Code generated by "stringer -type=opcode,MessageType,StatusCode -output=stringer.go"; DO NOT EDIT. + +package websocket + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[opContinuation-0] + _ = x[opText-1] + _ = x[opBinary-2] + _ = x[opClose-8] + _ = x[opPing-9] + _ = x[opPong-10] +} + +const ( + _opcode_name_0 = "opContinuationopTextopBinary" + _opcode_name_1 = "opCloseopPingopPong" +) + +var ( + _opcode_index_0 = [...]uint8{0, 14, 20, 28} + _opcode_index_1 = [...]uint8{0, 7, 13, 19} +) + +func (i opcode) String() string { + switch { + case 0 <= i && i <= 2: + return _opcode_name_0[_opcode_index_0[i]:_opcode_index_0[i+1]] + case 8 <= i && i <= 10: + i -= 8 + return _opcode_name_1[_opcode_index_1[i]:_opcode_index_1[i+1]] + default: + return "opcode(" + strconv.FormatInt(int64(i), 10) + ")" + } +} +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[MessageText-1] + _ = x[MessageBinary-2] +} + +const _MessageType_name = "MessageTextMessageBinary" + +var _MessageType_index = [...]uint8{0, 11, 24} + +func (i MessageType) String() string { + i -= 1 + if i < 0 || i >= MessageType(len(_MessageType_index)-1) { + return "MessageType(" + strconv.FormatInt(int64(i+1), 10) + ")" + } + return _MessageType_name[_MessageType_index[i]:_MessageType_index[i+1]] +} +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[StatusNormalClosure-1000] + _ = x[StatusGoingAway-1001] + _ = x[StatusProtocolError-1002] + _ = x[StatusUnsupportedData-1003] + _ = x[statusReserved-1004] + _ = x[StatusNoStatusRcvd-1005] + _ = x[StatusAbnormalClosure-1006] + _ = x[StatusInvalidFramePayloadData-1007] + _ = x[StatusPolicyViolation-1008] + _ = x[StatusMessageTooBig-1009] + _ = x[StatusMandatoryExtension-1010] + _ = x[StatusInternalError-1011] + _ = x[StatusServiceRestart-1012] + _ = x[StatusTryAgainLater-1013] + _ = x[StatusBadGateway-1014] + _ = x[StatusTLSHandshake-1015] +} + +const _StatusCode_name = "StatusNormalClosureStatusGoingAwayStatusProtocolErrorStatusUnsupportedDatastatusReservedStatusNoStatusRcvdStatusAbnormalClosureStatusInvalidFramePayloadDataStatusPolicyViolationStatusMessageTooBigStatusMandatoryExtensionStatusInternalErrorStatusServiceRestartStatusTryAgainLaterStatusBadGatewayStatusTLSHandshake" + +var _StatusCode_index = [...]uint16{0, 19, 34, 53, 74, 88, 106, 127, 156, 177, 196, 220, 239, 259, 278, 294, 312} + +func (i StatusCode) String() string { + i -= 1000 + if i < 0 || i >= StatusCode(len(_StatusCode_index)-1) { + return "StatusCode(" + strconv.FormatInt(int64(i+1000), 10) + ")" + } + return _StatusCode_name[_StatusCode_index[i]:_StatusCode_index[i+1]] +} diff --git a/vendor/nhooyr.io/websocket/write.go b/vendor/nhooyr.io/websocket/write.go new file mode 100644 index 0000000..2210cf8 --- /dev/null +++ b/vendor/nhooyr.io/websocket/write.go @@ -0,0 +1,397 @@ +// +build !js + +package websocket + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "io" + "time" + + "github.com/klauspost/compress/flate" + + "nhooyr.io/websocket/internal/errd" +) + +// Writer returns a writer bounded by the context that will write +// a WebSocket message of type dataType to the connection. +// +// You must close the writer once you have written the entire message. +// +// Only one writer can be open at a time, multiple calls will block until the previous writer +// is closed. +func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) { + w, err := c.writer(ctx, typ) + if err != nil { + return nil, fmt.Errorf("failed to get writer: %w", err) + } + return w, nil +} + +// Write writes a message to the connection. +// +// See the Writer method if you want to stream a message. +// +// If compression is disabled or the threshold is not met, then it +// will write the message in a single frame. +func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error { + _, err := c.write(ctx, typ, p) + if err != nil { + return fmt.Errorf("failed to write msg: %w", err) + } + return nil +} + +type msgWriter struct { + mw *msgWriterState + closed bool +} + +func (mw *msgWriter) Write(p []byte) (int, error) { + if mw.closed { + return 0, errors.New("cannot use closed writer") + } + return mw.mw.Write(p) +} + +func (mw *msgWriter) Close() error { + if mw.closed { + return errors.New("cannot use closed writer") + } + mw.closed = true + return mw.mw.Close() +} + +type msgWriterState struct { + c *Conn + + mu *mu + writeMu *mu + + ctx context.Context + opcode opcode + flate bool + + trimWriter *trimLastFourBytesWriter + dict slidingWindow +} + +func newMsgWriterState(c *Conn) *msgWriterState { + mw := &msgWriterState{ + c: c, + mu: newMu(c), + writeMu: newMu(c), + } + return mw +} + +func (mw *msgWriterState) ensureFlate() { + if mw.trimWriter == nil { + mw.trimWriter = &trimLastFourBytesWriter{ + w: writerFunc(mw.write), + } + } + + mw.dict.init(8192) + mw.flate = true +} + +func (mw *msgWriterState) flateContextTakeover() bool { + if mw.c.client { + return !mw.c.copts.clientNoContextTakeover + } + return !mw.c.copts.serverNoContextTakeover +} + +func (c *Conn) writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) { + err := c.msgWriterState.reset(ctx, typ) + if err != nil { + return nil, err + } + return &msgWriter{ + mw: c.msgWriterState, + closed: false, + }, nil +} + +func (c *Conn) write(ctx context.Context, typ MessageType, p []byte) (int, error) { + mw, err := c.writer(ctx, typ) + if err != nil { + return 0, err + } + + if !c.flate() { + defer c.msgWriterState.mu.unlock() + return c.writeFrame(ctx, true, false, c.msgWriterState.opcode, p) + } + + n, err := mw.Write(p) + if err != nil { + return n, err + } + + err = mw.Close() + return n, err +} + +func (mw *msgWriterState) reset(ctx context.Context, typ MessageType) error { + err := mw.mu.lock(ctx) + if err != nil { + return err + } + + mw.ctx = ctx + mw.opcode = opcode(typ) + mw.flate = false + + mw.trimWriter.reset() + + return nil +} + +// Write writes the given bytes to the WebSocket connection. +func (mw *msgWriterState) Write(p []byte) (_ int, err error) { + err = mw.writeMu.lock(mw.ctx) + if err != nil { + return 0, fmt.Errorf("failed to write: %w", err) + } + defer mw.writeMu.unlock() + + defer func() { + if err != nil { + err = fmt.Errorf("failed to write: %w", err) + mw.c.close(err) + } + }() + + if mw.c.flate() { + // Only enables flate if the length crosses the + // threshold on the first frame + if mw.opcode != opContinuation && len(p) >= mw.c.flateThreshold { + mw.ensureFlate() + } + } + + if mw.flate { + err = flate.StatelessDeflate(mw.trimWriter, p, false, mw.dict.buf) + if err != nil { + return 0, err + } + mw.dict.write(p) + return len(p), nil + } + + return mw.write(p) +} + +func (mw *msgWriterState) write(p []byte) (int, error) { + n, err := mw.c.writeFrame(mw.ctx, false, mw.flate, mw.opcode, p) + if err != nil { + return n, fmt.Errorf("failed to write data frame: %w", err) + } + mw.opcode = opContinuation + return n, nil +} + +// Close flushes the frame to the connection. +func (mw *msgWriterState) Close() (err error) { + defer errd.Wrap(&err, "failed to close writer") + + err = mw.writeMu.lock(mw.ctx) + if err != nil { + return err + } + defer mw.writeMu.unlock() + + _, err = mw.c.writeFrame(mw.ctx, true, mw.flate, mw.opcode, nil) + if err != nil { + return fmt.Errorf("failed to write fin frame: %w", err) + } + + if mw.flate && !mw.flateContextTakeover() { + mw.dict.close() + } + mw.mu.unlock() + return nil +} + +func (mw *msgWriterState) close() { + if mw.c.client { + mw.c.writeFrameMu.forceLock() + putBufioWriter(mw.c.bw) + } + + mw.writeMu.forceLock() + mw.dict.close() +} + +func (c *Conn) writeControl(ctx context.Context, opcode opcode, p []byte) error { + ctx, cancel := context.WithTimeout(ctx, time.Second*5) + defer cancel() + + _, err := c.writeFrame(ctx, true, false, opcode, p) + if err != nil { + return fmt.Errorf("failed to write control frame %v: %w", opcode, err) + } + return nil +} + +// frame handles all writes to the connection. +func (c *Conn) writeFrame(ctx context.Context, fin bool, flate bool, opcode opcode, p []byte) (_ int, err error) { + err = c.writeFrameMu.lock(ctx) + if err != nil { + return 0, err + } + defer c.writeFrameMu.unlock() + + // If the state says a close has already been written, we wait until + // the connection is closed and return that error. + // + // However, if the frame being written is a close, that means its the close from + // the state being set so we let it go through. + c.closeMu.Lock() + wroteClose := c.wroteClose + c.closeMu.Unlock() + if wroteClose && opcode != opClose { + select { + case <-ctx.Done(): + return 0, ctx.Err() + case <-c.closed: + return 0, c.closeErr + } + } + + select { + case <-c.closed: + return 0, c.closeErr + case c.writeTimeout <- ctx: + } + + defer func() { + if err != nil { + select { + case <-c.closed: + err = c.closeErr + case <-ctx.Done(): + err = ctx.Err() + } + c.close(err) + err = fmt.Errorf("failed to write frame: %w", err) + } + }() + + c.writeHeader.fin = fin + c.writeHeader.opcode = opcode + c.writeHeader.payloadLength = int64(len(p)) + + if c.client { + c.writeHeader.masked = true + _, err = io.ReadFull(rand.Reader, c.writeHeaderBuf[:4]) + if err != nil { + return 0, fmt.Errorf("failed to generate masking key: %w", err) + } + c.writeHeader.maskKey = binary.LittleEndian.Uint32(c.writeHeaderBuf[:]) + } + + c.writeHeader.rsv1 = false + if flate && (opcode == opText || opcode == opBinary) { + c.writeHeader.rsv1 = true + } + + err = writeFrameHeader(c.writeHeader, c.bw, c.writeHeaderBuf[:]) + if err != nil { + return 0, err + } + + n, err := c.writeFramePayload(p) + if err != nil { + return n, err + } + + if c.writeHeader.fin { + err = c.bw.Flush() + if err != nil { + return n, fmt.Errorf("failed to flush: %w", err) + } + } + + select { + case <-c.closed: + return n, c.closeErr + case c.writeTimeout <- context.Background(): + } + + return n, nil +} + +func (c *Conn) writeFramePayload(p []byte) (n int, err error) { + defer errd.Wrap(&err, "failed to write frame payload") + + if !c.writeHeader.masked { + return c.bw.Write(p) + } + + maskKey := c.writeHeader.maskKey + for len(p) > 0 { + // If the buffer is full, we need to flush. + if c.bw.Available() == 0 { + err = c.bw.Flush() + if err != nil { + return n, err + } + } + + // Start of next write in the buffer. + i := c.bw.Buffered() + + j := len(p) + if j > c.bw.Available() { + j = c.bw.Available() + } + + _, err := c.bw.Write(p[:j]) + if err != nil { + return n, err + } + + maskKey = mask(maskKey, c.writeBuf[i:c.bw.Buffered()]) + + p = p[j:] + n += j + } + + return n, nil +} + +type writerFunc func(p []byte) (int, error) + +func (f writerFunc) Write(p []byte) (int, error) { + return f(p) +} + +// extractBufioWriterBuf grabs the []byte backing a *bufio.Writer +// and returns it. +func extractBufioWriterBuf(bw *bufio.Writer, w io.Writer) []byte { + var writeBuf []byte + bw.Reset(writerFunc(func(p2 []byte) (int, error) { + writeBuf = p2[:cap(p2)] + return len(p2), nil + })) + + bw.WriteByte(0) + bw.Flush() + + bw.Reset(w) + + return writeBuf +} + +func (c *Conn) writeError(code StatusCode, err error) { + c.setCloseErr(err) + c.writeClose(code, err.Error()) + c.close(nil) +} diff --git a/vendor/nhooyr.io/websocket/ws_js.go b/vendor/nhooyr.io/websocket/ws_js.go new file mode 100644 index 0000000..b87e32c --- /dev/null +++ b/vendor/nhooyr.io/websocket/ws_js.go @@ -0,0 +1,379 @@ +package websocket // import "nhooyr.io/websocket" + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "reflect" + "runtime" + "strings" + "sync" + "syscall/js" + + "nhooyr.io/websocket/internal/bpool" + "nhooyr.io/websocket/internal/wsjs" + "nhooyr.io/websocket/internal/xsync" +) + +// Conn provides a wrapper around the browser WebSocket API. +type Conn struct { + ws wsjs.WebSocket + + // read limit for a message in bytes. + msgReadLimit xsync.Int64 + + closingMu sync.Mutex + isReadClosed xsync.Int64 + closeOnce sync.Once + closed chan struct{} + closeErrOnce sync.Once + closeErr error + closeWasClean bool + + releaseOnClose func() + releaseOnMessage func() + + readSignal chan struct{} + readBufMu sync.Mutex + readBuf []wsjs.MessageEvent +} + +func (c *Conn) close(err error, wasClean bool) { + c.closeOnce.Do(func() { + runtime.SetFinalizer(c, nil) + + if !wasClean { + err = fmt.Errorf("unclean connection close: %w", err) + } + c.setCloseErr(err) + c.closeWasClean = wasClean + close(c.closed) + }) +} + +func (c *Conn) init() { + c.closed = make(chan struct{}) + c.readSignal = make(chan struct{}, 1) + + c.msgReadLimit.Store(32768) + + c.releaseOnClose = c.ws.OnClose(func(e wsjs.CloseEvent) { + err := CloseError{ + Code: StatusCode(e.Code), + Reason: e.Reason, + } + // We do not know if we sent or received this close as + // its possible the browser triggered it without us + // explicitly sending it. + c.close(err, e.WasClean) + + c.releaseOnClose() + c.releaseOnMessage() + }) + + c.releaseOnMessage = c.ws.OnMessage(func(e wsjs.MessageEvent) { + c.readBufMu.Lock() + defer c.readBufMu.Unlock() + + c.readBuf = append(c.readBuf, e) + + // Lets the read goroutine know there is definitely something in readBuf. + select { + case c.readSignal <- struct{}{}: + default: + } + }) + + runtime.SetFinalizer(c, func(c *Conn) { + c.setCloseErr(errors.New("connection garbage collected")) + c.closeWithInternal() + }) +} + +func (c *Conn) closeWithInternal() { + c.Close(StatusInternalError, "something went wrong") +} + +// Read attempts to read a message from the connection. +// The maximum time spent waiting is bounded by the context. +func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error) { + if c.isReadClosed.Load() == 1 { + return 0, nil, errors.New("WebSocket connection read closed") + } + + typ, p, err := c.read(ctx) + if err != nil { + return 0, nil, fmt.Errorf("failed to read: %w", err) + } + if int64(len(p)) > c.msgReadLimit.Load() { + err := fmt.Errorf("read limited at %v bytes", c.msgReadLimit.Load()) + c.Close(StatusMessageTooBig, err.Error()) + return 0, nil, err + } + return typ, p, nil +} + +func (c *Conn) read(ctx context.Context) (MessageType, []byte, error) { + select { + case <-ctx.Done(): + c.Close(StatusPolicyViolation, "read timed out") + return 0, nil, ctx.Err() + case <-c.readSignal: + case <-c.closed: + return 0, nil, c.closeErr + } + + c.readBufMu.Lock() + defer c.readBufMu.Unlock() + + me := c.readBuf[0] + // We copy the messages forward and decrease the size + // of the slice to avoid reallocating. + copy(c.readBuf, c.readBuf[1:]) + c.readBuf = c.readBuf[:len(c.readBuf)-1] + + if len(c.readBuf) > 0 { + // Next time we read, we'll grab the message. + select { + case c.readSignal <- struct{}{}: + default: + } + } + + switch p := me.Data.(type) { + case string: + return MessageText, []byte(p), nil + case []byte: + return MessageBinary, p, nil + default: + panic("websocket: unexpected data type from wsjs OnMessage: " + reflect.TypeOf(me.Data).String()) + } +} + +// Ping is mocked out for Wasm. +func (c *Conn) Ping(ctx context.Context) error { + return nil +} + +// Write writes a message of the given type to the connection. +// Always non blocking. +func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error { + err := c.write(ctx, typ, p) + if err != nil { + // Have to ensure the WebSocket is closed after a write error + // to match the Go API. It can only error if the message type + // is unexpected or the passed bytes contain invalid UTF-8 for + // MessageText. + err := fmt.Errorf("failed to write: %w", err) + c.setCloseErr(err) + c.closeWithInternal() + return err + } + return nil +} + +func (c *Conn) write(ctx context.Context, typ MessageType, p []byte) error { + if c.isClosed() { + return c.closeErr + } + switch typ { + case MessageBinary: + return c.ws.SendBytes(p) + case MessageText: + return c.ws.SendText(string(p)) + default: + return fmt.Errorf("unexpected message type: %v", typ) + } +} + +// Close closes the WebSocket with the given code and reason. +// It will wait until the peer responds with a close frame +// or the connection is closed. +// It thus performs the full WebSocket close handshake. +func (c *Conn) Close(code StatusCode, reason string) error { + err := c.exportedClose(code, reason) + if err != nil { + return fmt.Errorf("failed to close WebSocket: %w", err) + } + return nil +} + +func (c *Conn) exportedClose(code StatusCode, reason string) error { + c.closingMu.Lock() + defer c.closingMu.Unlock() + + ce := fmt.Errorf("sent close: %w", CloseError{ + Code: code, + Reason: reason, + }) + + if c.isClosed() { + return fmt.Errorf("tried to close with %q but connection already closed: %w", ce, c.closeErr) + } + + c.setCloseErr(ce) + err := c.ws.Close(int(code), reason) + if err != nil { + return err + } + + <-c.closed + if !c.closeWasClean { + return c.closeErr + } + return nil +} + +// Subprotocol returns the negotiated subprotocol. +// An empty string means the default protocol. +func (c *Conn) Subprotocol() string { + return c.ws.Subprotocol() +} + +// DialOptions represents the options available to pass to Dial. +type DialOptions struct { + // Subprotocols lists the subprotocols to negotiate with the server. + Subprotocols []string +} + +// Dial creates a new WebSocket connection to the given url with the given options. +// The passed context bounds the maximum time spent waiting for the connection to open. +// The returned *http.Response is always nil or a mock. It's only in the signature +// to match the core API. +func Dial(ctx context.Context, url string, opts *DialOptions) (*Conn, *http.Response, error) { + c, resp, err := dial(ctx, url, opts) + if err != nil { + return nil, nil, fmt.Errorf("failed to WebSocket dial %q: %w", url, err) + } + return c, resp, nil +} + +func dial(ctx context.Context, url string, opts *DialOptions) (*Conn, *http.Response, error) { + if opts == nil { + opts = &DialOptions{} + } + + url = strings.Replace(url, "http://", "ws://", 1) + url = strings.Replace(url, "https://", "wss://", 1) + + ws, err := wsjs.New(url, opts.Subprotocols) + if err != nil { + return nil, nil, err + } + + c := &Conn{ + ws: ws, + } + c.init() + + opench := make(chan struct{}) + releaseOpen := ws.OnOpen(func(e js.Value) { + close(opench) + }) + defer releaseOpen() + + select { + case <-ctx.Done(): + c.Close(StatusPolicyViolation, "dial timed out") + return nil, nil, ctx.Err() + case <-opench: + return c, &http.Response{ + StatusCode: http.StatusSwitchingProtocols, + }, nil + case <-c.closed: + return nil, nil, c.closeErr + } +} + +// Reader attempts to read a message from the connection. +// The maximum time spent waiting is bounded by the context. +func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error) { + typ, p, err := c.Read(ctx) + if err != nil { + return 0, nil, err + } + return typ, bytes.NewReader(p), nil +} + +// Writer returns a writer to write a WebSocket data message to the connection. +// It buffers the entire message in memory and then sends it when the writer +// is closed. +func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) { + return writer{ + c: c, + ctx: ctx, + typ: typ, + b: bpool.Get(), + }, nil +} + +type writer struct { + closed bool + + c *Conn + ctx context.Context + typ MessageType + + b *bytes.Buffer +} + +func (w writer) Write(p []byte) (int, error) { + if w.closed { + return 0, errors.New("cannot write to closed writer") + } + n, err := w.b.Write(p) + if err != nil { + return n, fmt.Errorf("failed to write message: %w", err) + } + return n, nil +} + +func (w writer) Close() error { + if w.closed { + return errors.New("cannot close closed writer") + } + w.closed = true + defer bpool.Put(w.b) + + err := w.c.Write(w.ctx, w.typ, w.b.Bytes()) + if err != nil { + return fmt.Errorf("failed to close writer: %w", err) + } + return nil +} + +// CloseRead implements *Conn.CloseRead for wasm. +func (c *Conn) CloseRead(ctx context.Context) context.Context { + c.isReadClosed.Store(1) + + ctx, cancel := context.WithCancel(ctx) + go func() { + defer cancel() + c.read(ctx) + c.Close(StatusPolicyViolation, "unexpected data message") + }() + return ctx +} + +// SetReadLimit implements *Conn.SetReadLimit for wasm. +func (c *Conn) SetReadLimit(n int64) { + c.msgReadLimit.Store(n) +} + +func (c *Conn) setCloseErr(err error) { + c.closeErrOnce.Do(func() { + c.closeErr = fmt.Errorf("WebSocket closed: %w", err) + }) +} + +func (c *Conn) isClosed() bool { + select { + case <-c.closed: + return true + default: + return false + } +} diff --git a/vendor/nhooyr.io/websocket/ws_js_test.go b/vendor/nhooyr.io/websocket/ws_js_test.go new file mode 100644 index 0000000..e6be618 --- /dev/null +++ b/vendor/nhooyr.io/websocket/ws_js_test.go @@ -0,0 +1,38 @@ +package websocket_test + +import ( + "context" + "net/http" + "os" + "testing" + "time" + + "nhooyr.io/websocket" + "nhooyr.io/websocket/internal/test/assert" + "nhooyr.io/websocket/internal/test/wstest" +) + +func TestWasm(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + + c, resp, err := websocket.Dial(ctx, os.Getenv("WS_ECHO_SERVER_URL"), &websocket.DialOptions{ + Subprotocols: []string{"echo"}, + }) + assert.Success(t, err) + defer c.Close(websocket.StatusInternalError, "") + + assert.Equal(t, "subprotocol", "echo", c.Subprotocol()) + assert.Equal(t, "response code", http.StatusSwitchingProtocols, resp.StatusCode) + + c.SetReadLimit(65536) + for i := 0; i < 10; i++ { + err = wstest.Echo(ctx, c, 65536) + assert.Success(t, err) + } + + err = c.Close(websocket.StatusNormalClosure, "") + assert.Success(t, err) +} diff --git a/vendor/nhooyr.io/websocket/wsjson/wsjson.go b/vendor/nhooyr.io/websocket/wsjson/wsjson.go new file mode 100644 index 0000000..2000a77 --- /dev/null +++ b/vendor/nhooyr.io/websocket/wsjson/wsjson.go @@ -0,0 +1,67 @@ +// Package wsjson provides helpers for reading and writing JSON messages. +package wsjson // import "nhooyr.io/websocket/wsjson" + +import ( + "context" + "encoding/json" + "fmt" + + "nhooyr.io/websocket" + "nhooyr.io/websocket/internal/bpool" + "nhooyr.io/websocket/internal/errd" +) + +// Read reads a JSON message from c into v. +// It will reuse buffers in between calls to avoid allocations. +func Read(ctx context.Context, c *websocket.Conn, v interface{}) error { + return read(ctx, c, v) +} + +func read(ctx context.Context, c *websocket.Conn, v interface{}) (err error) { + defer errd.Wrap(&err, "failed to read JSON message") + + _, r, err := c.Reader(ctx) + if err != nil { + return err + } + + b := bpool.Get() + defer bpool.Put(b) + + _, err = b.ReadFrom(r) + if err != nil { + return err + } + + err = json.Unmarshal(b.Bytes(), v) + if err != nil { + c.Close(websocket.StatusInvalidFramePayloadData, "failed to unmarshal JSON") + return fmt.Errorf("failed to unmarshal JSON: %w", err) + } + + return nil +} + +// Write writes the JSON message v to c. +// It will reuse buffers in between calls to avoid allocations. +func Write(ctx context.Context, c *websocket.Conn, v interface{}) error { + return write(ctx, c, v) +} + +func write(ctx context.Context, c *websocket.Conn, v interface{}) (err error) { + defer errd.Wrap(&err, "failed to write JSON message") + + w, err := c.Writer(ctx, websocket.MessageText) + if err != nil { + return err + } + + // json.Marshal cannot reuse buffers between calls as it has to return + // a copy of the byte slice but Encoder does as it directly writes to w. + err = json.NewEncoder(w).Encode(v) + if err != nil { + return fmt.Errorf("failed to marshal JSON: %w", err) + } + + return w.Close() +} diff --git a/vendor/nhooyr.io/websocket/wspb/wspb.go b/vendor/nhooyr.io/websocket/wspb/wspb.go new file mode 100644 index 0000000..e43042d --- /dev/null +++ b/vendor/nhooyr.io/websocket/wspb/wspb.go @@ -0,0 +1,73 @@ +// Package wspb provides helpers for reading and writing protobuf messages. +package wspb // import "nhooyr.io/websocket/wspb" + +import ( + "bytes" + "context" + "fmt" + + "github.com/golang/protobuf/proto" + + "nhooyr.io/websocket" + "nhooyr.io/websocket/internal/bpool" + "nhooyr.io/websocket/internal/errd" +) + +// Read reads a protobuf message from c into v. +// It will reuse buffers in between calls to avoid allocations. +func Read(ctx context.Context, c *websocket.Conn, v proto.Message) error { + return read(ctx, c, v) +} + +func read(ctx context.Context, c *websocket.Conn, v proto.Message) (err error) { + defer errd.Wrap(&err, "failed to read protobuf message") + + typ, r, err := c.Reader(ctx) + if err != nil { + return err + } + + if typ != websocket.MessageBinary { + c.Close(websocket.StatusUnsupportedData, "expected binary message") + return fmt.Errorf("expected binary message for protobuf but got: %v", typ) + } + + b := bpool.Get() + defer bpool.Put(b) + + _, err = b.ReadFrom(r) + if err != nil { + return err + } + + err = proto.Unmarshal(b.Bytes(), v) + if err != nil { + c.Close(websocket.StatusInvalidFramePayloadData, "failed to unmarshal protobuf") + return fmt.Errorf("failed to unmarshal protobuf: %w", err) + } + + return nil +} + +// Write writes the protobuf message v to c. +// It will reuse buffers in between calls to avoid allocations. +func Write(ctx context.Context, c *websocket.Conn, v proto.Message) error { + return write(ctx, c, v) +} + +func write(ctx context.Context, c *websocket.Conn, v proto.Message) (err error) { + defer errd.Wrap(&err, "failed to write protobuf message") + + b := bpool.Get() + pb := proto.NewBuffer(b.Bytes()) + defer func() { + bpool.Put(bytes.NewBuffer(pb.Bytes())) + }() + + err = pb.Marshal(v) + if err != nil { + return fmt.Errorf("failed to marshal protobuf: %w", err) + } + + return c.Write(ctx, websocket.MessageBinary, pb.Bytes()) +} diff --git a/walletapi/balance_decoder.go b/walletapi/balance_decoder.go index e76a7b5..7d01b0f 100644 --- a/walletapi/balance_decoder.go +++ b/walletapi/balance_decoder.go @@ -16,22 +16,22 @@ package walletapi -import "os" +import "runtime" import "fmt" import "sort" import "math/big" import "encoding/binary" -import "github.com/mattn/go-isatty" -import "github.com/cheggaaa/pb/v3" +//import "github.com/mattn/go-isatty" +//import "github.com/cheggaaa/pb/v3" import "github.com/deroproject/derohe/crypto" import "github.com/deroproject/derohe/crypto/bn256" -// this file implements balance decoder whih has to be bruteforce +// this file implements balance decoder whih has to be bruteforced // balance is a 64 bit field and total effort is 2^64 // but in reality, the balances are well distributed with the expectation that no one will ever be able to collect over 2 ^ 40 -// However, 2^40 is solvable in less than 1 sec on a single core, with around 128 MB RAM, see below +// However, 2^40 is solvable in less than 1 sec on a single core, with around 8 MB RAM, see below // these tables are sharable between wallets //type PreComputeTable [16*1024*1024]uint64 // each table is 128 MB in size @@ -57,56 +57,80 @@ func (p PreComputeTable) Len() int { return len(p) } func (p PreComputeTable) Less(i, j int) bool { return p[i] < p[j] } func (p PreComputeTable) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +var precompute_table_ready = make(chan int) + // with some more smartness table can be condensed more to contain 16.3% more entries within the same size func Initialize_LookupTable(count int, table_size int) *LookupTable { t := make([]PreComputeTable, count, count) - terminal := isatty.IsTerminal(os.Stdout.Fd()) + if table_size&0xff != 0 { + panic("table size must be multiple of 256") + } - var acc, tmp bn256.G1 // avoid allocations every loop + //terminal := isatty.IsTerminal(os.Stdout.Fd()) + + var acc bn256.G1 // avoid allocations every loop acc.ScalarMult(crypto.G, new(big.Int).SetUint64(0)) + small_table := make([]*bn256.G1, 256, 256) + for k := range small_table { + small_table[k] = new(bn256.G1) + } + + var compressed [33]byte + for i := range t { t[i] = make([]uint64, table_size, table_size) - bar := pb.New(table_size) - if terminal { - bar.Start() - } - for j := range (t)[i] { - tmp.Set(&acc) + //bar := pb.New(table_size) + //if terminal { + // bar.Start() + //} + for j := 0; j < table_size; j += 256 { - if terminal { - bar.Increment() + for k := range small_table { + small_table[k].Set(&acc) + acc.Add(small_table[k], crypto.G) } + (bn256.G1Array(small_table)).MakeAffine() // precompute everything ASAP - // convert acc to compressed point and extract last 5 bytes - compressed := acc.EncodeCompressed() + //if terminal { + // bar.Add(256) + //} - // replace last bytes by j in coded form - compressed[32] = byte(uint64(j) & 0xff) - compressed[31] = byte((uint64(j) >> 8) & 0xff) - compressed[30] = byte((uint64(j) >> 16) & 0xff) + for k := range small_table { + // convert acc to compressed point and extract last 5 bytes + //compressed := small_table[k].EncodeCompressed() + small_table[k].EncodeCompressedToBuf(compressed[:]) - (t)[i][j] = binary.BigEndian.Uint64(compressed[25:]) - acc.Add(&tmp, crypto.G) + // replace last bytes by j in coded form + compressed[32] = byte(uint64(j+k) & 0xff) + compressed[31] = byte((uint64(j+k) >> 8) & 0xff) + compressed[30] = byte((uint64(j+k) >> 16) & 0xff) + + (t)[i][j+k] = binary.BigEndian.Uint64(compressed[25:]) + } // if j < 300 { // fmt.Printf("%d[%d]th entry %x\n",i,j, (t)[i][j]) // } - //if j % 10000 == 0 { - // fmt.Printf("completed %f (j %d)\n", float32(j)*100/float32(len((t)[i])), j) - //} + if j%1000 == 0 && runtime.GOOS == "js" { + fmt.Printf("completed %f (j %d)\n", float32(j)*100/float32(len((t)[i])), j) + runtime.Gosched() // gives others opportunity to run + } } //fmt.Printf("sorting start\n") sort.Sort(t[i]) //fmt.Printf("sortingcomplete\n") - bar.Finish() + //bar.Finish() } //fmt.Printf("lookuptable complete\n") t1 := LookupTable(t) + + Balance_lookup_table = &t1 + close(precompute_table_ready) return &t1 } @@ -118,6 +142,7 @@ func (t *LookupTable) Lookup(p *bn256.G1, previous_balance uint64) (balance uint //fmt.Printf("decoding balance now\n",) var acc bn256.G1 + <-precompute_table_ready // wait till precompute table is ready // check if previous balance is still sane though it may have mutated acc.ScalarMult(crypto.G, new(big.Int).SetUint64(previous_balance)) diff --git a/walletapi/cipher.go b/walletapi/cipher.go index a08d00c..7c47408 100644 --- a/walletapi/cipher.go +++ b/walletapi/cipher.go @@ -63,11 +63,11 @@ func DecryptWithKey(Key []byte, Data []byte) (result []byte, err error) { } // use master keys, everytime required -func (w *Wallet) Encrypt(Data []byte) (result []byte, err error) { +func (w *Wallet_Memory) Encrypt(Data []byte) (result []byte, err error) { return EncryptWithKey(w.master_password, Data) } // use master keys, everytime required -func (w *Wallet) Decrypt(Data []byte) (result []byte, err error) { +func (w *Wallet_Memory) Decrypt(Data []byte) (result []byte, err error) { return DecryptWithKey(w.master_password, Data) } diff --git a/walletapi/daemon_communication.go b/walletapi/daemon_communication.go index f68ba97..85b56b5 100644 --- a/walletapi/daemon_communication.go +++ b/walletapi/daemon_communication.go @@ -25,15 +25,11 @@ package walletapi //import "io" //import "os" import "fmt" -import "net" import "time" import "sync" import "bytes" import "math/big" -//import "net/url" -import "net/http" - //import "bufio" import "strings" import "context" @@ -47,52 +43,77 @@ import "runtime/debug" import "github.com/romana/rlog" -//import "github.com/pierrec/lz4" -import "github.com/ybbus/jsonrpc" - //import "github.com/vmihailenco/msgpack" //import "github.com/gorilla/websocket" //import "github.com/mafredri/cdp/rpcc" -import "github.com/deroproject/derohe/config" import "github.com/deroproject/derohe/block" import "github.com/deroproject/derohe/address" import "github.com/deroproject/derohe/crypto" -import "github.com/deroproject/derohe/globals" import "github.com/deroproject/derohe/errormsg" import "github.com/deroproject/derohe/structures" import "github.com/deroproject/derohe/transaction" import "github.com/deroproject/derohe/crypto/bn256" -import "github.com/deroproject/derohe/glue/rwc" import "github.com/creachadair/jrpc2" -import "github.com/creachadair/jrpc2/channel" -import "github.com/gorilla/websocket" // this global variable should be within wallet structure var Connected bool = false // there should be no global variables, so multiple wallets can run at the same time with different assset -var rpcClient *jsonrpc.RPCClient -var netClient *http.Client + var endpoint string var output_lock sync.Mutex -type Client struct { - WS *websocket.Conn - RPC *jrpc2.Client +var NotifyNewBlock *sync.Cond = sync.NewCond(&sync.Mutex{}) +var NotifyHeightChange *sync.Cond = sync.NewCond(&sync.Mutex{}) + +// this function will wait n goroutines to wait for new block +func WaitNewBlock() { + NotifyNewBlock.L.Lock() + NotifyNewBlock.Wait() + NotifyNewBlock.L.Unlock() } -var rpc_client = &Client{} +// this function will wait n goroutines to wait till height changes +func WaitNewHeightBlock() { + NotifyHeightChange.L.Lock() + NotifyHeightChange.Wait() + NotifyHeightChange.L.Unlock() +} + +func Notify_broadcaster(req *jrpc2.Request) { + + timer.Reset(timeout) // connection is alive + switch req.Method() { + + case "Repoll": + NotifyNewBlock.L.Lock() + NotifyNewBlock.Broadcast() + NotifyNewBlock.L.Unlock() + case "HRepoll": + NotifyHeightChange.L.Lock() + NotifyHeightChange.Broadcast() + NotifyHeightChange.L.Unlock() + default: + rlog.Debugf("Notification received %s\n", req.Method()) + } + +} + +// triggers syncing with wallet every 5 seconds +func (w *Wallet_Memory) sync_loop() { + w.Sync_Wallet_Memory_With_Daemon() // sync with the daemon +} func (cli *Client) Call(method string, params interface{}, result interface{}) error { return cli.RPC.CallResult(context.Background(), method, params, result) } // returns whether wallet was online some time ago -func (w *Wallet) IsDaemonOnlineCached() bool { +func (w *Wallet_Memory) IsDaemonOnlineCached() bool { return Connected } @@ -108,236 +129,56 @@ func buildurl(endpoint string) string { // this is as simple as it gets // single threaded communication to get the daemon status and height // this will tell whether the wallet can connection successfully to daemon or not -func (w *Wallet) IsDaemonOnline() bool { +func IsDaemonOnline() bool { if rpc_client.WS == nil || rpc_client.RPC == nil { return false } return true } -// this is as simple as it gets -// single threaded communication to get the daemon status and height -// this will tell whether the wallet can connection successfully to daemon or not -func (w *Wallet) Connect() (err error) { - - if globals.Arguments["--remote"] == true && globals.IsMainnet() { - w.Daemon_Endpoint = config.REMOTE_DAEMON - } - - // if user provided endpoint has error, use default - if w.Daemon_Endpoint == "" { - w.Daemon_Endpoint = "127.0.0.1:" + fmt.Sprintf("%d", config.Mainnet.RPC_Default_Port) - if !globals.IsMainnet() { - w.Daemon_Endpoint = "127.0.0.1:" + fmt.Sprintf("%d", config.Testnet.RPC_Default_Port) - } - } - - if globals.Arguments["--daemon-address"] != nil { - w.Daemon_Endpoint = globals.Arguments["--daemon-address"].(string) - } - - rlog.Infof("Daemon endpoint %s", w.Daemon_Endpoint) - - // TODO enable socks support here - var netTransport = &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 5 * time.Second, // 5 second timeout - }).Dial, - TLSHandshakeTimeout: 5 * time.Second, - } - - netClient = &http.Client{ - Timeout: time.Second * 10, - Transport: netTransport, - } - - //rpc_conn, err = rpcc.Dial("ws://"+ w.Daemon_Endpoint + "/ws") - - rpc_client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+w.Daemon_Endpoint+"/ws", nil) - - // notify user of any state change - // if daemon connection breaks or comes live again - if err == nil { - if !Connected { - rlog.Infof("Connection to RPC server successful %s", "ws://"+w.Daemon_Endpoint+"/ws") - Connected = true - } - } else { - rlog.Errorf("Error executing getinfo_rpc err %s", err) - - if Connected { - rlog.Warnf("Connection to RPC server Failed err %s endpoint %s ", err, "ws://"+w.Daemon_Endpoint+"/ws") - } - Connected = false - - return - } - - input_output := rwc.New(rpc_client.WS) - rpc_client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), nil) - - var result string - - // Issue a call with a response. - if err = rpc_client.Call("DERO.Echo", []string{"hello", "world"}, &result); err != nil { - rlog.Warnf("DERO.Echo Call failed: %v", err) - Connected = false - return - } - //fmt.Println(result) - - var info structures.GetInfo_Result - // Issue a call with a response. - if err = rpc_client.Call("DERO.GetInfo", nil, &info); err != nil { - rlog.Warnf("DERO.GetInfo Call failed: %v", err) - Connected = false - return - } - - // detect whether both are in different modes - // daemon is in testnet and wallet in mainnet or - // daemon - if info.Testnet != !globals.IsMainnet() { - err = fmt.Errorf("Mainnet/TestNet is different between wallet/daemon.Please run daemon/wallet without --testnet") - rlog.Criticalf("%s", err) - return - } - - w.random_ring_members() - - w.Lock() - defer w.Unlock() - - if info.Height >= 0 { - w.Daemon_Height = uint64(info.Height) - w.Daemon_TopoHeight = info.TopoHeight - w.Merkle_Balance_TreeHash = info.Merkle_Balance_TreeHash - } - w.dynamic_fees_per_kb = info.Dynamic_fee_per_kb // set fee rate, it can work for quite some time, - - // fmt.Printf("merkle tree %+v\n", info); - - return nil -} - -/* -func (cli *Client)onlinecheck_and_get_online(){ - for { - if cli.IsDaemonOnline() { - var result string - if err := cli.Call( "DERO.Ping", nil, &result); err != nil { - // fmt.Printf("Ping failed: %v", err) - cli.RPC.Close() - cli.WS = nil - cli.RPC = nil - Connect() // try to connect again - }else{ - //fmt.Printf("Ping Received %s\n", result) - } - } - time.Sleep(time.Second) - } -} -*/ - -// get the outputs from the daemon, requesting specfic outputs -// the range can be anything -// if stop is zero, -// the daemon will flush out everything it has ASAP -// the stream can be saved and used later on - -func (w *Wallet) Sync_Wallet_With_Daemon() { - - //fmt.Printf("syncing with wallet started\n") - - if !w.IsDaemonOnline() { - return - } - output_lock.Lock() - defer output_lock.Unlock() - - // fmt.Printf("account %+v\n", w.account) - - // only sync if both height are different - //if w.Daemon_TopoHeight == w.account.TopoHeight && w.account.TopoHeight != 0 { // wallet is already synced - // return - //} - - //w.Daemon_State_Version = "" - - w.random_ring_members() - - rlog.Infof("wallet topo height %d daemon online topo height %d\n", w.account.TopoHeight, w.Daemon_TopoHeight) - - previous := w.account.Balance_Result.Data - - if _, err := w.GetEncryptedBalance("", w.GetAddress().String()); err != nil { - return - } - - if w.account.Balance_Result.Data != previous || (len(w.account.Entries) >= 1 && strings.ToLower(w.account.Balance_Result.Data) != strings.ToLower(w.account.Entries[len(w.account.Entries)-1].EWData)) { - w.DecodeEncryptedBalance() // try to decode balance - w.SyncHistory() // also update statement - } - - return -} - -// triggers syncing with wallet every 5 seconds -func (w *Wallet) sync_loop() { - +// sync the wallet with daemon, this is instantaneous and can be done with a single call +// we have now the apis to avoid polling +func (w *Wallet_Memory) Sync_Wallet_Memory_With_Daemon() { + first_time := true for { + select { + case <-w.quit: + break + default: - if !Connected { - w.Connect() - } else { - if w.IsDaemonOnline() { - var result string - if err := rpc_client.Call("DERO.Ping", nil, &result); err != nil { - // fmt.Printf("Ping failed: %v", err) - rpc_client.RPC.Close() - rpc_client.WS = nil - rpc_client.RPC = nil - w.Connect() // try to connect again + } - } else { - //fmt.Printf("Ping Received %s\n", result) + if (first_time && IsDaemonOnline()) || (!first_time && IsDaemonOnline()) { + first_time = false + w.random_ring_members() + rlog.Debugf("wallet topo height %d daemon online topo height %d\n", w.account.TopoHeight, w.Daemon_TopoHeight) + previous := w.account.Balance_Result.Data + if _, err := w.GetEncryptedBalance("", w.GetAddress().String()); err == nil { + if w.account.Balance_Result.Data != previous || (len(w.account.Entries) >= 1 && strings.ToLower(w.account.Balance_Result.Data) != strings.ToLower(w.account.Entries[len(w.account.Entries)-1].EWData)) { + w.DecodeEncryptedBalance() // try to decode balance + w.SyncHistory() // also update statement } + } else { + rlog.Infof("getbalance err %s", err) } } + time.Sleep(timeout) // wait 5 seconds - if w.IsDaemonOnline() { // could not connect try again after 5 secs - w.Sync_Wallet_With_Daemon() // sync with the daemon - } - - select { // quit midway if required - case <-w.quit: - return - case <-time.After(5 * time.Second): - } - - if !w.wallet_online_mode { // wallet requested to be in offline mode - return - } } -} - -func (w *Wallet) Rescan_From_Height(startheight uint64) { - panic("not implemented") - + return } // this is as simple as it gets // single threaded communication to relay TX to daemon // if this is successful, then daemon is in control -func (w *Wallet) SendTransaction(tx *transaction.Transaction) (err error) { +func (w *Wallet_Memory) SendTransaction(tx *transaction.Transaction) (err error) { if tx == nil { return fmt.Errorf("Can not send nil transaction") } - if !w.IsDaemonOnline() { + if !IsDaemonOnline() { return fmt.Errorf("offline or not connected. cannot send transaction.") } @@ -368,7 +209,7 @@ func (w *Wallet) SendTransaction(tx *transaction.Transaction) (err error) { // TODO in order to stop privacy leaks we must guess this information somehow on client side itself // maybe the server can broadcast a bloomfilter or something else from the mempool keyimages // -func (w *Wallet) GetEncryptedBalance(treehash string, accountaddr string) (e *crypto.ElGamal, err error) { +func (w *Wallet_Memory) GetEncryptedBalance(treehash string, accountaddr string) (e *crypto.ElGamal, err error) { defer func() { if r := recover(); r != nil { @@ -382,7 +223,7 @@ func (w *Wallet) GetEncryptedBalance(treehash string, accountaddr string) (e *cr return } - if !w.IsDaemonOnline() { + if !IsDaemonOnline() { err = fmt.Errorf("offline or not connected") return } @@ -431,7 +272,7 @@ func (w *Wallet) GetEncryptedBalance(treehash string, accountaddr string) (e *cr return el, nil } -func (w *Wallet) DecodeEncryptedBalance() (err error) { +func (w *Wallet_Memory) DecodeEncryptedBalance() (err error) { var el crypto.ElGamal var balance_point bn256.G1 @@ -460,7 +301,7 @@ func (w *Wallet) DecodeEncryptedBalance() (err error) { // TODO in order to stop privacy leaks we must guess this information somehow on client side itself // maybe the server can broadcast a bloomfilter or something else from the mempool keyimages // -func (w *Wallet) GetEncryptedBalanceAtTopoHeight(topoheight int64, accountaddr string) (e *crypto.ElGamal, err error) { +func (w *Wallet_Memory) GetEncryptedBalanceAtTopoHeight(topoheight int64, accountaddr string) (e *crypto.ElGamal, err error) { defer func() { if r := recover(); r != nil { @@ -474,7 +315,7 @@ func (w *Wallet) GetEncryptedBalanceAtTopoHeight(topoheight int64, accountaddr s return } - if !w.IsDaemonOnline() { + if !IsDaemonOnline() { err = fmt.Errorf("offline or not connected") return } @@ -538,7 +379,7 @@ func (w *Wallet) GetEncryptedBalanceAtTopoHeight(topoheight int64, accountaddr s return el, nil } -func (w *Wallet) DecodeEncryptedBalance_Memory(el *crypto.ElGamal, hint uint64) (balance uint64) { +func (w *Wallet_Memory) DecodeEncryptedBalance_Memory(el *crypto.ElGamal, hint uint64) (balance uint64) { var balance_point bn256.G1 @@ -547,7 +388,7 @@ func (w *Wallet) DecodeEncryptedBalance_Memory(el *crypto.ElGamal, hint uint64) return Balance_lookup_table.Lookup(&balance_point, hint) } -func (w *Wallet) GetDecryptedBalanceAtTopoHeight(topoheight int64, accountaddr string) (balance uint64, err error) { +func (w *Wallet_Memory) GetDecryptedBalanceAtTopoHeight(topoheight int64, accountaddr string) (balance uint64, err error) { encrypted_balance, err := w.GetEncryptedBalanceAtTopoHeight(topoheight, accountaddr) if err != nil { return 0, err @@ -557,7 +398,7 @@ func (w *Wallet) GetDecryptedBalanceAtTopoHeight(topoheight int64, accountaddr s } // sync history of wallet from blockchain -func (w *Wallet) random_ring_members() { +func (w *Wallet_Memory) random_ring_members() { //fmt.Printf("getting random_ring_members\n") @@ -588,7 +429,7 @@ func (w *Wallet) random_ring_members() { } // sync history of wallet from blockchain -func (w *Wallet) SyncHistory() (balance uint64) { +func (w *Wallet_Memory) SyncHistory() (balance uint64) { if w.account.Balance_Result.Registration < 0 { // unregistered so skip return } @@ -658,7 +499,7 @@ func (w *Wallet) SyncHistory() (balance uint64) { } // sync history -func (w *Wallet) synchistory_internal(start_topo, end_topo int64) error { +func (w *Wallet_Memory) synchistory_internal(start_topo, end_topo int64) error { var err error var start_balance_e *crypto.ElGamal @@ -680,7 +521,7 @@ func (w *Wallet) synchistory_internal(start_topo, end_topo int64) error { } -func (w *Wallet) synchistory_internal_binary_search(start_topo int64, start_balance_e *crypto.ElGamal, end_topo int64, end_balance_e *crypto.ElGamal) error { +func (w *Wallet_Memory) synchistory_internal_binary_search(start_topo int64, start_balance_e *crypto.ElGamal, end_topo int64, end_balance_e *crypto.ElGamal) error { //fmt.Printf("end %d start %d\n", end_topo, start_topo) @@ -786,7 +627,7 @@ func (w *Wallet) synchistory_internal_binary_search(start_topo int64, start_bala // Todo we should expose an API to get all txs which have the specific address as ring member // for a particular block // for the entire chain -func (w *Wallet) synchistory_block(topo int64) (err error) { +func (w *Wallet_Memory) synchistory_block(topo int64) (err error) { var local_entries []Entry diff --git a/walletapi/daemon_connectivity.go b/walletapi/daemon_connectivity.go new file mode 100644 index 0000000..4ee63f2 --- /dev/null +++ b/walletapi/daemon_connectivity.go @@ -0,0 +1,134 @@ +// +build !wasm + +// Copyright 2017-2021 DERO Project. All rights reserved. +// Use of this source code in any form is governed by RESEARCH license. +// license can be found in the LICENSE file. +// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 +// +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package walletapi + +// this file needs serious improvements but have extremely limited time +/* this file handles communication with the daemon + * this includes receiving output information + * + * * + */ +//import "io" +//import "os" +import "fmt" + +//import "net/url" +import "net/http" + +import "github.com/romana/rlog" + +import "github.com/deroproject/derohe/config" +import "github.com/deroproject/derohe/globals" +import "github.com/deroproject/derohe/structures" + +import "github.com/deroproject/derohe/glue/rwc" + +import "github.com/creachadair/jrpc2" +import "github.com/creachadair/jrpc2/channel" +import "github.com/gorilla/websocket" + +// there should be no global variables, so multiple wallets can run at the same time with different assset + +var netClient *http.Client + +type Client struct { + WS *websocket.Conn + RPC *jrpc2.Client +} + +var rpc_client = &Client{} + +var Daemon_Endpoint string + +// this is as simple as it gets +// single threaded communication to get the daemon status and height +// this will tell whether the wallet can connection successfully to daemon or not +func Connect(endpoint string) (err error) { + + if globals.Arguments["--remote"] == true && globals.IsMainnet() { + Daemon_Endpoint = config.REMOTE_DAEMON + } + + // if user provided endpoint has error, use default + if Daemon_Endpoint == "" { + Daemon_Endpoint = "127.0.0.1:" + fmt.Sprintf("%d", config.Mainnet.RPC_Default_Port) + if !globals.IsMainnet() { + Daemon_Endpoint = "127.0.0.1:" + fmt.Sprintf("%d", config.Testnet.RPC_Default_Port) + } + } + + if globals.Arguments["--daemon-address"] != nil { + Daemon_Endpoint = globals.Arguments["--daemon-address"].(string) + } + + rlog.Infof("Daemon endpoint %s", Daemon_Endpoint) + + //rpc_conn, err = rpcc.Dial("ws://"+ w.Daemon_Endpoint + "/ws") + + rpc_client.WS, _, err = websocket.DefaultDialer.Dial("ws://"+Daemon_Endpoint+"/ws", nil) + + // notify user of any state change + // if daemon connection breaks or comes live again + if err == nil { + if !Connected { + rlog.Infof("Connection to RPC server successful %s", "ws://"+Daemon_Endpoint+"/ws") + Connected = true + } + } else { + rlog.Errorf("Error executing getinfo_rpc err %s", err) + + if Connected { + rlog.Warnf("Connection to RPC server Failed err %s endpoint %s ", err, "ws://"+Daemon_Endpoint+"/ws") + } + Connected = false + + return + } + + input_output := rwc.New(rpc_client.WS) + rpc_client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), &jrpc2.ClientOptions{OnNotify: Notify_broadcaster}) + + var result string + + // Issue a call with a response. + if err = rpc_client.Call("DERO.Echo", []string{"hello", "world"}, &result); err != nil { + rlog.Warnf("DERO.Echo Call failed: %v", err) + Connected = false + return + } + //fmt.Println(result) + + var info structures.GetInfo_Result + // Issue a call with a response. + if err = rpc_client.Call("DERO.GetInfo", nil, &info); err != nil { + rlog.Warnf("DERO.GetInfo Call failed: %v", err) + Connected = false + return + } + + // detect whether both are in different modes + // daemon is in testnet and wallet in mainnet or + // daemon + if info.Testnet != !globals.IsMainnet() { + err = fmt.Errorf("Mainnet/TestNet is different between wallet/daemon.Please run daemon/wallet without --testnet") + rlog.Criticalf("%s", err) + return + } + return nil +} diff --git a/walletapi/daemon_connectivity_loop.go b/walletapi/daemon_connectivity_loop.go new file mode 100644 index 0000000..6ce1397 --- /dev/null +++ b/walletapi/daemon_connectivity_loop.go @@ -0,0 +1,69 @@ +// Copyright 2017-2021 DERO Project. All rights reserved. +// Use of this source code in any form is governed by RESEARCH license. +// license can be found in the LICENSE file. +// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 +// +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package walletapi + +// this file needs serious improvements but have extremely limited time +/* this file handles communication with the daemon + * this includes receiving output information + * + * * + */ +//import "io" +//import "os" +//import "fmt" + +import "time" + +import _ "github.com/romana/rlog" + +var timeout = 5 * time.Second +var timer = time.NewTimer(time.Millisecond) + +// this function continously turns connectivity online/offline +// avoid connectivity calls when possible +func Keep_Connectivity() { + Connect("") + for { + select { + //case <- w.quit: + // return + case <-timer.C: // we disconnected and did not connect, this timer fires every 5 secs, + + timer.Reset(timeout) + if !Connected { + Connect("") + } else { + if IsDaemonOnline() { + var result string + if err := rpc_client.Call("DERO.Ping", nil, &result); err != nil { + // fmt.Printf("Ping failed: %v", err) + rpc_client.RPC.Close() + rpc_client.WS = nil + rpc_client.RPC = nil + Connected = false + Connect("") // try to connect again + + } else { + //fmt.Printf("Pong Received %s\n", result) + } + } + } + } + + } + +} diff --git a/walletapi/daemon_connectivity_wasm.go b/walletapi/daemon_connectivity_wasm.go new file mode 100644 index 0000000..20576d4 --- /dev/null +++ b/walletapi/daemon_connectivity_wasm.go @@ -0,0 +1,146 @@ +// Copyright 2017-2021 DERO Project. All rights reserved. +// Use of this source code in any form is governed by RESEARCH license. +// license can be found in the LICENSE file. +// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 +// +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package walletapi + +// this file needs serious improvements but have extremely limited time +/* this file handles communication with the daemon + * this includes receiving output information + * + * * + */ +//import "io" +//import "os" +import "fmt" +import "net" +import "time" + +import "context" +import "net/http" + +import "github.com/romana/rlog" + +import "github.com/deroproject/derohe/config" +import "github.com/deroproject/derohe/globals" +import "github.com/deroproject/derohe/structures" + +import "github.com/deroproject/derohe/glue/rwc" + +import "github.com/creachadair/jrpc2" +import "github.com/creachadair/jrpc2/channel" +import "nhooyr.io/websocket" + +// there should be no global variables, so multiple wallets can run at the same time with different assset + +var netClient *http.Client + +type Client struct { + WS *websocket.Conn + RPC *jrpc2.Client +} + +var rpc_client = &Client{} + +var Daemon_Endpoint string + +// this is as simple as it gets +// single threaded communication to get the daemon status and height +// this will tell whether the wallet can connection successfully to daemon or not +func Connect(endpoint string) (err error) { + + if globals.Arguments["--remote"] == true && globals.IsMainnet() { + Daemon_Endpoint = config.REMOTE_DAEMON + } + + // if user provided endpoint has error, use default + if Daemon_Endpoint == "" { + Daemon_Endpoint = "127.0.0.1:" + fmt.Sprintf("%d", config.Mainnet.RPC_Default_Port) + if !globals.IsMainnet() { + Daemon_Endpoint = "127.0.0.1:" + fmt.Sprintf("%d", config.Testnet.RPC_Default_Port) + } + } + + if globals.Arguments["--daemon-address"] != nil { + Daemon_Endpoint = globals.Arguments["--daemon-address"].(string) + } + + Daemon_Endpoint = "127.0.0.1:8080" + rlog.Infof("Daemon endpoint %s will connect ", Daemon_Endpoint) + + // TODO enable socks support here + var netTransport = &http.Transport{ + Dial: (&net.Dialer{ + Timeout: 5 * time.Second, // 5 second timeout + }).Dial, + TLSHandshakeTimeout: 5 * time.Second, + } + + netClient = &http.Client{ + Timeout: time.Second * 10, + Transport: netTransport, + } + + rpc_client.WS, _, err = websocket.Dial(context.Background(), "ws://"+Daemon_Endpoint+"/ws", nil) + + // notify user of any state change + // if daemon connection breaks or comes live again + if err == nil { + if !Connected { + rlog.Infof("Connection to RPC server successful %s", "ws://"+Daemon_Endpoint+"/ws") + Connected = true + } + } else { + rlog.Errorf("Error executing getinfo_rpc err %s", err) + + if Connected { + rlog.Warnf("Connection to RPC server Failed err %s endpoint %s ", err, "ws://"+Daemon_Endpoint+"/ws") + } + Connected = false + + return + } + + input_output := rwc.NewNhooyr(rpc_client.WS) + rpc_client.RPC = jrpc2.NewClient(channel.RawJSON(input_output, input_output), &jrpc2.ClientOptions{OnNotify: Notify_broadcaster}) + + var result string + + // Issue a call with a response. + if err = rpc_client.Call("DERO.Echo", []string{"hello", "world"}, &result); err != nil { + rlog.Warnf("DERO.Echo Call failed: %v", err) + Connected = false + return + } + //fmt.Println(result) + + var info structures.GetInfo_Result + // Issue a call with a response. + if err = rpc_client.Call("DERO.GetInfo", nil, &info); err != nil { + rlog.Warnf("DERO.GetInfo Call failed: %v", err) + Connected = false + return + } + + // detect whether both are in different modes + // daemon is in testnet and wallet in mainnet or + // daemon + if info.Testnet != !globals.IsMainnet() { + err = fmt.Errorf("Mainnet/TestNet is different between wallet/daemon.Please run daemon/wallet without --testnet") + rlog.Criticalf("%s", err) + return + } + return nil +} diff --git a/walletapi/db.go b/walletapi/db.go index 89f31d3..4daa2a6 100644 --- a/walletapi/db.go +++ b/walletapi/db.go @@ -1,3 +1,5 @@ +// +build !wasm + // Copyright 2017-2021 DERO Project. All rights reserved. // Use of this source code in any form is governed by RESEARCH license. // license can be found in the LICENSE file. @@ -19,369 +21,134 @@ package walletapi import "os" import "fmt" import "time" -import "crypto/rand" -import "crypto/sha1" import "sync" - -//import "strings" -//import "math/big" -//import "encoding/hex" -import "encoding/json" - -//import "encoding/binary" +import "io/ioutil" import "github.com/romana/rlog" -//import "github.com/vmihailenco/msgpack" - -import bolt "github.com/coreos/bbolt" -import "github.com/blang/semver" -import "golang.org/x/crypto/pbkdf2" // // used to encrypt master password ( so user can change his password anytime) - import "github.com/deroproject/derohe/crypto" import "github.com/deroproject/derohe/walletapi/mnemonics" -// address book will have random number based entries - -// see this https://godoc.org/golang.org/x/crypto/pbkdf2 -type KDF struct { - Hashfunction string `json:"hash"` //"SHA1" currently only sha1 is supported - Keylen int `json:"keylen"` - Iterations int `json:"iterations"` - Salt []byte `json:"salt"` -} - // this is stored in disk in encrypted form -type Wallet struct { - Version semver.Version `json:"version"` // database version - Secret []byte `json:"secret"` // actual unlocker to the DB, depends on password from user, stored encrypted - // secret key used to encrypt all DB data ( both keys and values ) - // this is always in encrypted form - - KDF KDF `json:"kdf"` - - account *Account //`json:"-"` // not serialized, we store an encrypted version // keys, seed language etc settings - Account_Encrypted []byte `json:"account_encrypted"` - - pbkdf2_password []byte // used to encrypt metadata on updates - master_password []byte // single password which never changes - - Daemon_Endpoint string `json:"-"` // endpoint used to communicate with daemon - Daemon_Height uint64 `json:"-"` // used to track daemon height ony if wallet in online - Daemon_TopoHeight int64 `json:"-"` // used to track daemon topo height ony if wallet in online - Merkle_Balance_TreeHash string `json:"-"` // current balance tree state - - wallet_online_mode bool // set whether the mode is online or offline - // an offline wallet can be converted to online mode, calling. - // SetOffline() and vice versa using SetOnline - // used to create transaction with this fee rate, - //if this is lower than network, then created transaction will be rejected by network - dynamic_fees_per_kb uint64 - quit chan bool // channel to quit any processing go routines - - db *bolt.DB // access to DB - - rpcserver *RPCServer // reference to RPCserver - - id string // first 8 bytes of wallet address , to put into logs to identify different wallets in case many are active - - Error error - - transfer_mutex sync.Mutex // to avoid races within the transfer - //sync.Mutex // used to syncronise access - sync.RWMutex +type Wallet_Disk struct { + *Wallet_Memory + filename string + sync.Mutex } -const META_BUCKET = "METADATA" // all metadata is stored in this bucket -const BLOCKS_BUCKET = "BLOCKS" // stores height to block hash mapping for later on syncing - -var BLOCKCHAIN_UNIVERSE = []byte("BLOCKCHAIN_UNIVERSE") // all main chain txs are stored in this bucket - // when smart contracts are implemented, each will have it's own universe to track and maintain transactions // this file implements the encrypted data store at rest -func Create_Encrypted_Wallet(filename string, password string, seed *crypto.BNRed) (w *Wallet, err error) { - rlog.Infof("Creating Wallet from recovery seed") - w = &Wallet{} - w.Version, err = semver.Parse("0.0.1-alpha.preview.github") - - if err != nil { - return - } +func Create_Encrypted_Wallet(filename string, password string, seed *crypto.BNRed) (w *Wallet_Disk, err error) { if _, err = os.Stat(filename); err == nil { err = fmt.Errorf("File '%s' already exists", filename) - rlog.Errorf("err creating wallet %s", err) return + + } else if os.IsNotExist(err) { + // path/to/whatever does *not* exist + // err = fmt.Errorf("path does not exists '%s'", filename) + } - w.db, err = bolt.Open(filename, 0600, &bolt.Options{Timeout: 1 * time.Second}) - - if err != nil { - rlog.Errorf("err opening boltdb file %s", err) - return - } + wd := &Wallet_Disk{filename: filename} // generate account keys - w.account, err = Generate_Account_From_Seed(seed) - if err != nil { - return + if wd.Wallet_Memory, err = Create_Encrypted_Wallet_Memory(password, seed); err != nil { + return nil, err } - // generate a 64 byte key to be used as master Key - w.master_password = make([]byte, 32, 32) - _, err = rand.Read(w.master_password) - if err != nil { - return - } - - err = w.Set_Encrypted_Wallet_Password(password) // lock the db with the password - - w.quit = make(chan bool) - - w.id = string((w.account.GetAddress().String())[:8]) // set unique id for logs - w.account.Balance_Result.Registration = -1 - - rlog.Infof("Successfully created wallet %s", w.id) return } // create an encrypted wallet using electrum recovery words -func Create_Encrypted_Wallet_From_Recovery_Words(filename string, password string, electrum_seed string) (w *Wallet, err error) { - rlog.Infof("Creating Wallet from recovery words") +func Create_Encrypted_Wallet_From_Recovery_Words(filename string, password string, electrum_seed string) (wd *Wallet_Disk, err error) { + wd = &Wallet_Disk{filename: filename} language, seed, err := mnemonics.Words_To_Key(electrum_seed) if err != nil { rlog.Errorf("err parsing recovery words %s", err) return } - w, err = Create_Encrypted_Wallet(filename, password, crypto.GetBNRed(seed)) - - if err != nil { + if wd.Wallet_Memory, err = Create_Encrypted_Wallet_Memory(password, crypto.GetBNRed(seed)); err != nil { rlog.Errorf("err creating wallet %s", err) - return + return nil, err } - w.account.SeedLanguage = language - rlog.Infof("Successfully created wallet %s", w.id) + wd.Wallet_Memory.account.SeedLanguage = language return } // create an encrypted wallet using using random data -func Create_Encrypted_Wallet_Random(filename string, password string) (w *Wallet, err error) { +func Create_Encrypted_Wallet_Random(filename string, password string) (wd *Wallet_Disk, err error) { rlog.Infof("Creating Wallet Randomly") - w, err = Create_Encrypted_Wallet(filename, password, crypto.RandomScalarBNRed()) - - if err != nil { - rlog.Errorf("err %s", err) - return + wd = &Wallet_Disk{filename: filename} + if wd.Wallet_Memory, err = Create_Encrypted_Wallet_Memory(password, crypto.RandomScalarBNRed()); err == nil { + return wd, nil } - // TODO setup seed language, default is already english - rlog.Infof("Successfully created wallet %s", w.id) - return + + return nil, err } // wallet must already be open -func (w *Wallet) Set_Encrypted_Wallet_Password(password string) (err error) { - - if w == nil { - return +func (w *Wallet_Disk) Set_Encrypted_Wallet_Password(password string) (err error) { + if w != nil { + w.Wallet_Memory.Set_Encrypted_Wallet_Password(password) + w.Save_Wallet() // save wallet data } - w.Lock() - - // set up KDF structure - w.KDF.Salt = make([]byte, 32, 32) - _, err = rand.Read(w.KDF.Salt) - if err != nil { - w.Unlock() - return - } - w.KDF.Keylen = 32 - w.KDF.Iterations = 262144 - w.KDF.Hashfunction = "SHA1" - - // lets generate the bcrypted password - - w.pbkdf2_password = Generate_Key(w.KDF, password) - - w.Unlock() - w.Save_Wallet() // save wallet data - return } -func Open_Encrypted_Wallet(filename string, password string) (w *Wallet, err error) { - w = &Wallet{} +func Open_Encrypted_Wallet(filename string, password string) (wd *Wallet_Disk, err error) { + wd = &Wallet_Disk{} + var filedata []byte if _, err = os.Stat(filename); os.IsNotExist(err) { err = fmt.Errorf("File '%s' does NOT exists", filename) rlog.Errorf("err opening wallet %s", err) - return + return nil, err } - w.db, err = bolt.Open(filename, 0600, &bolt.Options{Timeout: 1 * time.Second}) - - if err != nil { - rlog.Errorf("err opening boltdb %s", err) - return + if filedata, err = ioutil.ReadFile(filename); err != nil { + rlog.Errorf("err reading files %s", err) + return nil, err } - // read the metadata from metadat bucket - w.db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - b := tx.Bucket([]byte(META_BUCKET)) - - v := b.Get([]byte(META_BUCKET)) - - if v == nil || len(v) == 0 { - err = fmt.Errorf("Invalid Database, Could not find meta data") - rlog.Errorf("err opening wallet %s", err) - return err - } - - //fmt.Printf("v %+v\n",string(v)) // DO NOT dump account keys - - // deserialize json data - err = json.Unmarshal(v, &w) - if err != nil { - rlog.Errorf("err parsing metabucket %s", err) - return err - } - - w.quit = make(chan bool) - // todo make any routines necessary, such as sync etc - - return nil - }) - - // try to deseal password and store it - w.pbkdf2_password = Generate_Key(w.KDF, password) - - // try to decrypt the master password with the pbkdf2 - w.master_password, err = DecryptWithKey(w.pbkdf2_password, w.Secret) // decrypt the master key - if err != nil { - //rlog.Errorf("err opening secret err: %s ", err) - err = fmt.Errorf("Invalid Password") - w.db.Close() - w = nil - return + if wd.Wallet_Memory, err = Open_Encrypted_Wallet_Memory(password, filedata); err != nil { + return nil, err } - // password has been found, open the account - - account_bytes, err := w.Decrypt(w.Account_Encrypted) - if err != nil { - rlog.Errorf("err opening account err: %s ", err) - err = fmt.Errorf("Invalid Password") - w.db.Close() - w = nil - return - } - - w.account = &Account{} // allocate a new instance - err = json.Unmarshal(account_bytes, w.account) - if err != nil { - return - } - w.account.Balance_Result.Registration = -1 - return } // check whether the already opened wallet can use this password -func (w *Wallet) Check_Password(password string) bool { +func (w *Wallet_Disk) Check_Password(password string) bool { w.Lock() defer w.Unlock() - if w == nil { - return false - } - pbkdf2_password := Generate_Key(w.KDF, password) - - // TODO we can compare pbkdf2_password & w.pbkdf2_password, if they are equal password is vaid - - // try to decrypt the master password with the pbkdf2 - _, err := DecryptWithKey(pbkdf2_password, w.Secret) // decrypt the master key - - if err == nil { - return true - } - rlog.Warnf("%s Invalid Password", w.id) - return false + return w.Wallet_Memory.Check_Password(password) } // save updated copy of wallet -func (w *Wallet) Save_Wallet() (err error) { - w.Lock() - defer w.Unlock() +func (w *Wallet_Disk) Save_Wallet() (err error) { if w == nil { return } + w.Lock() + defer w.Unlock() - // encrypted the master password with the pbkdf2 - w.Secret, err = EncryptWithKey(w.pbkdf2_password[:], w.master_password) // encrypt the master key - if err != nil { + if err = w.Wallet_Memory.Save_Wallet(); err != nil { return } - // encrypt the account - - account_serialized, err := json.Marshal(w.account) - if err != nil { - return - } - - // fmt.Printf("account serialized %s\n", string(account_serialized)) - // fmt.Printf("account serialized full %+v %s\n", w.account , w.account.Keys.Secret.Text(16)) - - w.Account_Encrypted, err = w.Encrypt(account_serialized) - if err != nil { - return - } - - // json marshal wallet data struct, serialize it, encrypt it and store it - serialized, err := json.Marshal(&w) - if err != nil { - return - } - //fmt.Printf("Serialized %+v\n",serialized) - - // let save the secret to DISK in encrypted form - err = w.db.Update(func(tx *bolt.Tx) (err error) { - - bucket, err := tx.CreateBucketIfNotExists([]byte(META_BUCKET)) - if err != nil { - return - } - err = bucket.Put([]byte(META_BUCKET), serialized) - return - - }) - rlog.Infof("Saving wallet %s", w.id) - return + return ioutil.WriteFile(w.filename, w.Wallet_Memory.db_memory, 0600) } // close the wallet -func (w *Wallet) Close_Encrypted_Wallet() { - close(w.quit) - +func (w *Wallet_Disk) Close_Encrypted_Wallet() { time.Sleep(time.Second) // give goroutines some time to quit - rlog.Infof("Saving and Closing Wallet %s\n", w.id) w.Save_Wallet() - w.db.Sync() - - w.db.Close() -} - -// generate key from password -func Generate_Key(k KDF, password string) (key []byte) { - switch k.Hashfunction { - case "SHA1": - return pbkdf2.Key([]byte(password), k.Salt, k.Iterations, k.Keylen, sha1.New) - - default: - return pbkdf2.Key([]byte(password), k.Salt, k.Iterations, k.Keylen, sha1.New) - } + w.Wallet_Memory.Close_Encrypted_Wallet() } diff --git a/walletapi/db_memory.go b/walletapi/db_memory.go new file mode 100644 index 0000000..cd89961 --- /dev/null +++ b/walletapi/db_memory.go @@ -0,0 +1,334 @@ +// Copyright 2017-2021 DERO Project. All rights reserved. +// Use of this source code in any form is governed by RESEARCH license. +// license can be found in the LICENSE file. +// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 +// +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package walletapi + +import "fmt" +import "time" +import "crypto/rand" +import "crypto/sha1" +import "sync" +import "runtime" + +//import "strings" +//import "math/big" +//import "encoding/hex" +import "encoding/json" + +//import "encoding/binary" + +import "github.com/romana/rlog" + +//import "github.com/vmihailenco/msgpack" + +import "github.com/blang/semver" +import "golang.org/x/crypto/pbkdf2" // // used to encrypt master password ( so user can change his password anytime) + +import "github.com/deroproject/derohe/crypto" +import "github.com/deroproject/derohe/config" +import "github.com/deroproject/derohe/walletapi/mnemonics" + +// address book will have random number based entries + +// see this https://godoc.org/golang.org/x/crypto/pbkdf2 +type KDF struct { + Hashfunction string `json:"hash"` //"SHA1" currently only sha1 is supported + Keylen int `json:"keylen"` + Iterations int `json:"iterations"` + Salt []byte `json:"salt"` +} + +// this is stored in disk in encrypted form +type Wallet_Memory struct { + Version semver.Version `json:"version"` // database version + Secret []byte `json:"secret"` // actual unlocker to the DB, depends on password from user, stored encrypted + // secret key used to encrypt all DB data ( both keys and values ) + // this is always in encrypted form + + KDF KDF `json:"kdf"` + + account *Account //`json:"-"` // not serialized, we store an encrypted version // keys, seed language etc settings + Account_Encrypted []byte `json:"account_encrypted"` + + pbkdf2_password []byte // used to encrypt metadata on updates + master_password []byte // single password which never changes + + Daemon_Endpoint string `json:"-"` // endpoint used to communicate with daemon + Daemon_Height uint64 `json:"-"` // used to track daemon height ony if wallet in online + Daemon_TopoHeight int64 `json:"-"` // used to track daemon topo height ony if wallet in online + Merkle_Balance_TreeHash string `json:"-"` // current balance tree state + + wallet_online_mode bool // set whether the mode is online or offline + // an offline wallet can be converted to online mode, calling. + // SetOffline() and vice versa using SetOnline + // used to create transaction with this fee rate, + //if this is lower than network, then created transaction will be rejected by network + dynamic_fees_per_kb uint64 + quit chan bool // channel to quit any processing go routines + + db_memory []byte // all data is stored here + + id string // first 8 bytes of wallet address , to put into logs to identify different wallets in case many are active + + Error error `json:"-"` + + transfer_mutex sync.Mutex // to avoid races within the transfer + //sync.Mutex // used to syncronise access + sync.RWMutex +} + +// when smart contracts are implemented, each will have it's own universe to track and maintain transactions + +// this file implements the encrypted data store at rest +func Create_Encrypted_Wallet_Memory(password string, seed *crypto.BNRed) (w *Wallet_Memory, err error) { + rlog.Debugf("Creating Wallet from recovery seed") + w = &Wallet_Memory{} + w.Version = config.Version + + if err != nil { + return + } + + // generate account keys + w.account, err = Generate_Account_From_Seed(seed) + if err != nil { + return + } + + // generate a 64 byte key to be used as master Key + w.master_password = make([]byte, 32, 32) + _, err = rand.Read(w.master_password) + if err != nil { + return + } + + err = w.Set_Encrypted_Wallet_Password(password) // lock the db with the password + + w.quit = make(chan bool) + + w.id = string((w.account.GetAddress().String())[:8]) // set unique id for logs + w.account.Balance_Result.Registration = -1 + + rlog.Debugf("Successfully created wallet %s", w.id) + return +} + +// create an encrypted wallet using electrum recovery words +func Create_Encrypted_Wallet_From_Recovery_Words_Memory(password string, electrum_seed string) (w *Wallet_Memory, err error) { + rlog.Debugf("Creating Wallet from recovery words") + + language, seed, err := mnemonics.Words_To_Key(electrum_seed) + if err != nil { + rlog.Errorf("err parsing recovery words %s", err) + return + } + w, err = Create_Encrypted_Wallet_Memory(password, crypto.GetBNRed(seed)) + + if err != nil { + rlog.Errorf("err creating wallet %s", err) + return + } + + w.account.SeedLanguage = language + rlog.Infof("Successfully created wallet %s", w.id) + return +} + +// create an encrypted wallet using using random data +func Create_Encrypted_Wallet_Random_Memory(password string) (w *Wallet_Memory, err error) { + rlog.Infof("Creating Wallet Randomly") + w, err = Create_Encrypted_Wallet_Memory(password, crypto.RandomScalarBNRed()) + + if err != nil { + rlog.Errorf("err %s", err) + return + } + // TODO setup seed language, default is already english + rlog.Infof("Successfully created wallet %s", w.id) + return +} + +// wallet must already be open +func (w *Wallet_Memory) Set_Encrypted_Wallet_Password(password string) (err error) { + + if w == nil { + return + } + w.Lock() + + // set up KDF structure + w.KDF.Salt = make([]byte, 32, 32) + _, err = rand.Read(w.KDF.Salt) + if err != nil { + w.Unlock() + return + } + w.KDF.Keylen = 32 + w.KDF.Iterations = 262144 + w.KDF.Hashfunction = "SHA1" + + if runtime.GOOS == "js" { + w.KDF.Iterations = 32768 + } + + // lets generate the bcrypted password + + w.pbkdf2_password = Generate_Key(w.KDF, password) + + w.Unlock() + w.Save_Wallet() // save wallet data + + return +} + +func Open_Encrypted_Wallet_Memory(password string, filedata []byte) (w *Wallet_Memory, err error) { + w = &Wallet_Memory{} + + //fmt.Printf("v %+v\n",string(v)) // DO NOT dump account keys + + // deserialize json data + err = json.Unmarshal(filedata, &w) + if err != nil { + rlog.Errorf("err parsing metabucket %s", err) + return + } + + w.quit = make(chan bool) + // todo make any routines necessary, such as sync etc + + // try to deseal password and store it + w.pbkdf2_password = Generate_Key(w.KDF, password) + + // try to decrypt the master password with the pbkdf2 + w.master_password, err = DecryptWithKey(w.pbkdf2_password, w.Secret) // decrypt the master key + if err != nil { + //rlog.Errorf("err opening secret err: %s ", err) + err = fmt.Errorf("Invalid Password") + w = nil + return + } + + // password has been found, open the account + + account_bytes, err := w.Decrypt(w.Account_Encrypted) + if err != nil { + rlog.Errorf("err opening account err: %s ", err) + err = fmt.Errorf("Invalid Password") + w = nil + return + } + + w.account = &Account{} // allocate a new instance + err = json.Unmarshal(account_bytes, w.account) + if err != nil { + return + } + w.account.Balance_Result.Registration = -1 + + return + +} + +// check whether the already opened wallet can use this password +func (w *Wallet_Memory) Check_Password(password string) bool { + w.Lock() + defer w.Unlock() + if w == nil { + return false + } + + pbkdf2_password := Generate_Key(w.KDF, password) + + // TODO we can compare pbkdf2_password & w.pbkdf2_password, if they are equal password is vaid + + // try to decrypt the master password with the pbkdf2 + _, err := DecryptWithKey(pbkdf2_password, w.Secret) // decrypt the master key + + if err == nil { + return true + } + rlog.Warnf("%s Invalid Password", w.id) + return false + +} + +// save updated copy of wallet +func (w *Wallet_Memory) Save_Wallet() (err error) { + w.Lock() + defer w.Unlock() + if w == nil { + return + } + + // encrypted the master password with the pbkdf2 + w.Secret, err = EncryptWithKey(w.pbkdf2_password[:], w.master_password) // encrypt the master key + if err != nil { + return + } + + // encrypt the account + + account_serialized, err := json.Marshal(w.account) + if err != nil { + return + } + + // fmt.Printf("account serialized %s\n", string(account_serialized)) + // fmt.Printf("account serialized full %+v %s\n", w.account , w.account.Keys.Secret.Text(16)) + + w.Account_Encrypted, err = w.Encrypt(account_serialized) + if err != nil { + return + } + + // json marshal wallet data struct, serialize it, encrypt it and store it + serialized, err := json.Marshal(&w) + if err != nil { + return + } + //fmt.Printf("Serialized %+v\n",serialized) + + w.db_memory = serialized + rlog.Infof("Saving wallet %s", w.id) + return +} + +// get encrypted wallet +func (w *Wallet_Memory) Get_Encrypted_Wallet() []byte { + if err := w.Save_Wallet(); err == nil { + return w.db_memory + } + return []byte{} +} + +// close the wallet +// note that w is still valid and can be used to obtaine encrypted copy of data +func (w *Wallet_Memory) Close_Encrypted_Wallet() { + time.Sleep(time.Second) // give goroutines some time to quit + rlog.Infof("Saving and Closing Wallet %s\n", w.id) + w.Save_Wallet() +} + +// generate key from password +func Generate_Key(k KDF, password string) (key []byte) { + switch k.Hashfunction { + case "SHA1": + return pbkdf2.Key([]byte(password), k.Salt, k.Iterations, k.Keylen, sha1.New) + + default: + return pbkdf2.Key([]byte(password), k.Salt, k.Iterations, k.Keylen, sha1.New) + } +} diff --git a/walletapi/key_to_key.go b/walletapi/key_to_key.go deleted file mode 100644 index f914219..0000000 --- a/walletapi/key_to_key.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017-2021 DERO Project. All rights reserved. -// Use of this source code in any form is governed by RESEARCH license. -// license can be found in the LICENSE file. -// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 -// -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package walletapi - -import "crypto/sha256" - -// all keys are derived as follows ( entirely deterministic ) -// ( key is derived from master secret and user supplied key) -// it's only 1 way -// all keys and bucket names are stored using this , except the metadata bucket -// all values are stored using salsa20 aead -// since all keys are dependent on the master password, almost 99.99% analsis are rendered useless -func (w *Wallet) Key2Key(Key []byte) []byte { - h := sha256.New() - h.Write(w.master_password) - h.Write(Key) - hash := h.Sum(nil) - return hash[:] -} diff --git a/walletapi/mnemonics/mnemonics.go b/walletapi/mnemonics/mnemonics.go index 3d7d07d..91d709f 100644 --- a/walletapi/mnemonics/mnemonics.go +++ b/walletapi/mnemonics/mnemonics.go @@ -72,7 +72,7 @@ func Language_List() (list []string) { //this function converts a list of words to a key func Words_To_Key(words_line string) (language_name string, keybig *big.Int, err error) { - var key [32]byte + var key [32]byte checksum_present := false words := strings.Fields(words_line) //rlog.Tracef(1, "len of words %d", words) @@ -128,7 +128,7 @@ func Words_To_Key(words_line string) (language_name string, keybig *big.Int, err //fmt.Printf("words %+v\n", indices) //fmt.Printf("key %x\n", key) - keybig = new(big.Int).SetBytes(key[:]) + keybig = new(big.Int).SetBytes(key[:]) return } @@ -136,7 +136,7 @@ func Words_To_Key(words_line string) (language_name string, keybig *big.Int, err // this will map the key to recovery words from the spcific language // language must exist,if not we return english func Key_To_Words(keybig *big.Int, language string) (words_line string) { - var key [32]byte + var key [32]byte var words []string // all words are appended here l_index := 0 @@ -147,15 +147,14 @@ func Key_To_Words(keybig *big.Int, language string) (words_line string) { } } - // FillBytes not available pre 1.15 - bb := keybig.Bytes() - j := 32 - for i := len(bb)-1; i >= 0; i-- { - j-- - key[j] = bb[i] - - } + // FillBytes not available pre 1.15 + bb := keybig.Bytes() + j := 32 + for i := len(bb) - 1; i >= 0; i-- { + j-- + key[j] = bb[i] + } // total numbers of words in specified language dictionary word_list_length := uint32(len(Languages[l_index].Words)) diff --git a/walletapi/rpc_transfersplit.go b/walletapi/rpc_transfersplit.go deleted file mode 100644 index a26938f..0000000 --- a/walletapi/rpc_transfersplit.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2017-2018 DERO Project. All rights reserved. -// Use of this source code in any form is governed by RESEARCH license. -// license can be found in the LICENSE file. -// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 -// -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package walletapi - -import "fmt" -import "context" -import "encoding/hex" -import "encoding/json" - -//import "log" -//import "net/http" - -import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - -import "github.com/deroproject/derohe/globals" -import "github.com/deroproject/derohe/address" -import "github.com/deroproject/derohe/structures" - -type TransferSplit_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h TransferSplit_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - var p structures.TransferSplit_Params - var result structures.TransferSplit_Result - var err error - - h.r.Lock() - defer h.r.Unlock() - rlog.Debugf("transfer split handler") - defer rlog.Debugf("transfer split handler finished") - - if errp := jsonrpc.Unmarshal(params, &p); err != nil { - rlog.Errorf("Could not parse incoming json, err %s\n", errp) - return nil, errp - } - - //if len(p.Destinations) < 1 || p.Mixin < 4 { - // return nil, jsonrpc.ErrInvalidParams() - //} - - rlog.Debugf("Len destinations %d %+v", len(p.Destinations), p) - - unlock_time := p.Unlock_time - payment_id := p.Payment_ID - if len(payment_id) > 0 && (len(payment_id) == 64 || len(payment_id) == 16) != true { - return nil, jsonrpc.ErrInvalidParams() // we should give invalid payment ID - } - if _, err := hex.DecodeString(p.Payment_ID); err != nil { - return nil, jsonrpc.ErrInvalidParams() // we should give invalid payment ID - } - rlog.Debugf("Payment ID %s", payment_id) - - b, err := json.Marshal(p) - if err == nil { - rlog.Debugf("Request can be repeated using below command") - - rlog.Debugf(`curl -X POST http://127.0.0.1:18092/json_rpc -d '{"jsonrpc":"2.0","id":"0","method":"transfer_split","params":%s}' -H 'Content-Type: application/json'`, string(b)) - } - - var address_list []address.Address - var amount_list []uint64 - for i := range p.Destinations { - a, err := globals.ParseValidateAddress(p.Destinations[i].Address) - if err != nil { - rlog.Errorf("Parsing address failed %s err %s\n", p.Destinations[i].Address, err) - return nil, jsonrpc.ErrInvalidParams() - } - address_list = append(address_list, *a) - amount_list = append(amount_list, p.Destinations[i].Amount) - - } - - fees_per_kb := uint64(0) // fees must be calculated by walletapi - if !h.r.w.GetMode() { // if wallet is in online mode, use the fees, provided by the daemon, else we need to use what is provided by the user - - // TODO - } - tx, err := h.r.w.Transfer(address_list, amount_list, unlock_time, payment_id, fees_per_kb, p.Mixin, false) - if err != nil { - rlog.Warnf("Error while building Transaction err %s\n", err) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Error while building Transaction err %s", err)} - - } - - amount := uint64(0) - for i := range amount_list { - amount += amount_list[i] - } - - if p.Do_not_relay == false { // we do not relay the tx, the user must submit it manually - err = h.r.w.SendTransaction(tx) - - if err == nil { - rlog.Infof("Transaction sent successfully. txid = %s", tx.GetHash()) - } else { - rlog.Warnf("Transaction sending failed txid = %s, err %s", tx.GetHash(), err) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Transaction sending failed txid = %s, err %s", tx.GetHash(), err)} - } - - } - - result.Fee_list = append(result.Fee_list, tx.Statement.Fees) - result.Tx_hash_list = append(result.Tx_hash_list, tx.GetHash().String()) - if p.Get_tx_hex { // request need TX blobs, give them - result.Tx_blob_list = append(result.Tx_blob_list, hex.EncodeToString(tx.SerializeHeader())) - } - // - //extract secret key and feed it in here - if p.Get_tx_key { - result.Tx_key_list = append(result.Tx_key_list, h.r.w.GetTXKey(tx.GetHash())) //TODO - } - - return result, nil -} diff --git a/walletapi/rpcserver.go b/walletapi/rpcserver.go deleted file mode 100644 index e0396d3..0000000 --- a/walletapi/rpcserver.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2017-2021 DERO Project. All rights reserved. -// Use of this source code in any form is governed by RESEARCH license. -// license can be found in the LICENSE file. -// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 -// -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// the rpc server is an extension of walletapi and doesnot employ any global variables -// so a number can be simultaneously active ( based on resources) -package walletapi - -import "io" - -//import "fmt" -import "time" -import "sync" -import "log" -import "strings" -import "net/http" - -//import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - -import "github.com/deroproject/derohe/globals" -import "github.com/deroproject/derohe/structures" - -// all components requiring access to wallet must use , this struct to communicate -// this structure must be update while mutex -type RPCServer struct { - address string - srv *http.Server - mux *http.ServeMux - mr *jsonrpc.MethodRepository - Exit_Event chan bool // wallet is shutting down and we must quit ASAP - Exit_In_Progress bool - - w *Wallet // reference to the wallet which is open - sync.RWMutex -} - -func RPCServer_Start(w *Wallet, address string) (*RPCServer, error) { - - //var err error - var r RPCServer - - //_ = err - - r.Exit_Event = make(chan bool) - r.w = w - r.address = address - - go r.Run() - //logger.Infof("RPC server started") - - return &r, nil -} - -// shutdown the rpc server component -func (r *RPCServer) RPCServer_Stop() { - r.srv.Shutdown(nil) // shutdown the server - r.Exit_In_Progress = true - close(r.Exit_Event) // send signal to all connections to exit - // TODO we must wait for connections to kill themselves - time.Sleep(1 * time.Second) - //logger.Infof("RPC Shutdown") - -} - -func (r *RPCServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { - - basic_auth_enabled := false - var parts []string - - if globals.Arguments["--rpc-login"] != nil { - userpass := globals.Arguments["--rpc-login"].(string) - parts = strings.SplitN(userpass, ":", 2) - - basic_auth_enabled = true - /*if len(parts) != 2 { // these checks are done and verified during program init - globals.Logger.Warnf("RPC user name or password invalid") - return - }*/ - //log.Infof("RPC username \"%s\" password \"%s\" ", parts[0],parts[1]) - } - - if basic_auth_enabled { - u, p, ok := req.BasicAuth() - if !ok { - http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - if u != parts[0] || p != parts[1] { - http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - - } - // log.Printf("basic_auth_handler") serve if everything looks okay - r.mr.ServeHTTP(w, req) -} - -// setup handlers -func (r *RPCServer) Run() { - - mr := jsonrpc.NewMethodRepository() - r.mr = mr - - // install getbalance handler - if err := mr.RegisterMethod("getbalance", GetBalance_Handler{r: r}, structures.GetBalance_Params{}, structures.GetBalance_Result{}); err != nil { - log.Fatalln(err) - } - - // install getaddress handler - if err := mr.RegisterMethod("getaddress", GetAddress_Handler{r: r}, structures.GetAddress_Params{}, structures.GetBalance_Result{}); err != nil { - log.Fatalln(err) - } - - // install getheight handler - if err := mr.RegisterMethod("getheight", GetHeight_Handler{r: r}, structures.GetHeight_Params{}, structures.GetBalance_Result{}); err != nil { - log.Fatalln(err) - } - - // install transfer handler - if err := mr.RegisterMethod("transfer", Transfer_Handler{r: r}, structures.Transfer_Params{}, structures.Transfer_Result{}); err != nil { - log.Fatalln(err) - } - // install transfer_split handler - if err := mr.RegisterMethod("transfer_split", TransferSplit_Handler{r: r}, structures.TransferSplit_Params{}, structures.TransferSplit_Result{}); err != nil { - log.Fatalln(err) - } - - // install get_bulk_payments handler - if err := mr.RegisterMethod("get_bulk_payments", Get_Bulk_Payments_Handler{r: r}, structures.Get_Bulk_Payments_Params{}, structures.Get_Bulk_Payments_Result{}); err != nil { - log.Fatalln(err) - } - - // install query_key handler - if err := mr.RegisterMethod("query_key", Query_Key_Handler{r: r}, structures.Query_Key_Params{}, structures.Query_Key_Result{}); err != nil { - log.Fatalln(err) - } - - // install make_integrated_address handler - if err := mr.RegisterMethod("make_integrated_address", Make_Integrated_Address_Handler{r: r}, structures.Make_Integrated_Address_Params{}, structures.Make_Integrated_Address_Result{}); err != nil { - log.Fatalln(err) - } - - // install split_integrated_address handler - if err := mr.RegisterMethod("split_integrated_address", Split_Integrated_Address_Handler{r: r}, structures.Split_Integrated_Address_Params{}, structures.Split_Integrated_Address_Result{}); err != nil { - log.Fatalln(err) - } - - // install get_transfer_by_txid handler - if err := mr.RegisterMethod("get_transfer_by_txid", Get_Transfer_By_TXID_Handler{r: r}, structures.Get_Transfer_By_TXID_Params{}, structures.Get_Transfer_By_TXID_Result{}); err != nil { - log.Fatalln(err) - } - - // install get_transfers - if err := mr.RegisterMethod("get_transfers", Get_Transfers_Handler{r: r}, structures.Get_Transfers_Params{}, structures.Get_Transfers_Result{}); err != nil { - log.Fatalln(err) - } - - /* - if err := mr.RegisterMethod("Main.Echo", EchoHandler{}, EchoParams{}, EchoResult{}); err != nil { - log.Fatalln(err) - } - - // install getblockcount handler - if err := mr.RegisterMethod("getblockcount", GetBlockCount_Handler{}, structures.GetBlockCount_Params{}, structures.GetBlockCount_Result{}); err != nil { - log.Fatalln(err) - } - - // install on_getblockhash - if err := mr.RegisterMethod("on_getblockhash", On_GetBlockHash_Handler{}, structures.On_GetBlockHash_Params{}, structures.On_GetBlockHash_Result{}); err != nil { - log.Fatalln(err) - } - - // install getblocktemplate handler - if err := mr.RegisterMethod("getblocktemplate", GetBlockTemplate_Handler{}, structures.GetBlockTemplate_Params{}, structures.GetBlockTemplate_Result{}); err != nil { - log.Fatalln(err) - } - - // submitblock handler - if err := mr.RegisterMethod("submitblock", SubmitBlock_Handler{}, structures.SubmitBlock_Params{}, structures.SubmitBlock_Result{}); err != nil { - log.Fatalln(err) - } - - if err := mr.RegisterMethod("getlastblockheader", GetLastBlockHeader_Handler{}, structures.GetLastBlockHeader_Params{}, structures.GetLastBlockHeader_Result{}); err != nil { - log.Fatalln(err) - } - - if err := mr.RegisterMethod("getblockheaderbyhash", GetBlockHeaderByHash_Handler{}, structures.GetBlockHeaderByHash_Params{}, structures.GetBlockHeaderByHash_Result{}); err != nil { - log.Fatalln(err) - } - - if err := mr.RegisterMethod("getblockheaderbyheight", GetBlockHeaderByHeight_Handler{}, structures.GetBlockHeaderByHeight_Params{}, structures.GetBlockHeaderByHeight_Result{}); err != nil { - log.Fatalln(err) - } - if err := mr.RegisterMethod("getblock", GetBlock_Handler{}, structures.GetBlock_Params{}, structures.GetBlock_Result{}); err != nil { - log.Fatalln(err) - } - - if err := mr.RegisterMethod("get_info", GetInfo_Handler{}, structures.GetInfo_Params{}, structures.GetInfo_Result{}); err != nil { - log.Fatalln(err) - } - - if err := mr.RegisterMethod("gettxpool", GetTxPool_Handler{}, structures.GetTxPool_Params{}, structures.GetTxPool_Result{}); err != nil { - log.Fatalln(err) - } - - */ - // create a new mux - r.mux = http.NewServeMux() - r.srv = &http.Server{Addr: r.address, Handler: r.mux} - - r.mux.HandleFunc("/", hello) - r.mux.Handle("/json_rpc", r) - /* - // handle nasty http requests - r.mux.HandleFunc("/getoutputs.bin", getoutputs) // stream any outputs to server, can make wallet work offline - r.mux.HandleFunc("/gettransactions", gettransactions) - r.mux.HandleFunc("/sendrawtransaction", SendRawTransaction_Handler) - */ - //r.mux.HandleFunc("/json_rpc/debug", mr.ServeDebug) - - if err := r.srv.ListenAndServe(); err != http.ErrServerClosed { - log.Fatalf("ERR listening to address err %s", err) - } - -} - -func hello(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Hello world!") -} diff --git a/walletapi/rpc_get_bulk_payments.go b/walletapi/rpcserver/rpc_get_bulk_payments.go similarity index 65% rename from walletapi/rpc_get_bulk_payments.go rename to walletapi/rpcserver/rpc_get_bulk_payments.go index ec41836..9491c45 100644 --- a/walletapi/rpc_get_bulk_payments.go +++ b/walletapi/rpcserver/rpc_get_bulk_payments.go @@ -14,43 +14,28 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver import "fmt" import "context" +import "runtime/debug" import "encoding/hex" -//import "log" -//import "net/http" - -import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - import "github.com/deroproject/derohe/structures" -type Get_Bulk_Payments_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h Get_Bulk_Payments_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - var p structures.Get_Bulk_Payments_Params - var result structures.Get_Bulk_Payments_Result - //var result structures.Transfer_Result - //var err error - - if errp := jsonrpc.Unmarshal(params, &p); errp != nil { - rlog.Errorf("Could not parse gettransfers json, err %s\n", errp) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Could not parse gettransfers json, err %s", errp)} - } +func (w *WALLET_RPC_APIS) GetBulkPayments(ctx context.Context, p structures.Get_Bulk_Payments_Params) (result structures.Get_Bulk_Payments_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() // if no payment ID provided, provide all entries with payment ID // but this is a heavy call, // south exchange needed this compatibility if len(p.Payment_IDs) == 0 { - entries := h.r.w.Show_Transfers(true, true, false, false, false, true, p.Min_block_height, 0) + entries := w.wallet.Show_Transfers(true, true, false, false, false, true, p.Min_block_height, 0) for j := range entries { result.Payments = append(result.Payments, structures.Transfer_Details{TXID: entries[j].TXID.String(), @@ -69,15 +54,15 @@ func (h Get_Bulk_Payments_Handler) ServeJSONRPC(c context.Context, params *fastj for i := range p.Payment_IDs { payid, err := hex.DecodeString(p.Payment_IDs[i]) if err != nil { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("%s could NOT be hex decoded err %s", p.Payment_IDs[i], err)} + return result, fmt.Errorf("%s could NOT be hex decoded err %s", p.Payment_IDs[i], err) } - if !(len(payid) == 8 || len(payid) == 32) { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("%s not 16 or 64 hex bytes", p.Payment_IDs[i])} + if len(payid) != 8 { + return result, fmt.Errorf("%s not 16 hex bytes", p.Payment_IDs[i]) } // if everything is okay, fire the query and convert the result to output format - entries := h.r.w.Get_Payments_Payment_ID(payid, p.Min_block_height) + entries := w.wallet.Get_Payments_Payment_ID(payid, p.Min_block_height) for j := range entries { result.Payments = append(result.Payments, structures.Transfer_Details{TXID: entries[j].TXID.String(), Payment_ID: hex.EncodeToString(entries[j].PaymentID), diff --git a/walletapi/rpc_get_transfer_by_txid.go b/walletapi/rpcserver/rpc_get_transfer_by_txid.go similarity index 63% rename from walletapi/rpc_get_transfer_by_txid.go rename to walletapi/rpcserver/rpc_get_transfer_by_txid.go index d07521d..8eeddf8 100644 --- a/walletapi/rpc_get_transfer_by_txid.go +++ b/walletapi/rpcserver/rpc_get_transfer_by_txid.go @@ -14,48 +14,32 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver import "fmt" import "context" +import "runtime/debug" import "encoding/hex" - -//import "log" -//import "net/http" - -import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - import "github.com/deroproject/derohe/structures" -type Get_Transfer_By_TXID_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h Get_Transfer_By_TXID_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - var p structures.Get_Transfer_By_TXID_Params - var result structures.Get_Transfer_By_TXID_Result - //var result structures.Transfer_Result - //var err error - - if errp := jsonrpc.Unmarshal(params, &p); errp != nil { - rlog.Errorf("Could not parse get_transfer_by_txid json, err %s\n", errp) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Could not parse get_transfer_by_txid json, err %s", errp)} - } +func (w *WALLET_RPC_APIS) GetTransferbyTXID(ctx context.Context, p structures.Get_Transfer_By_TXID_Params) (result structures.Get_Transfer_By_TXID_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() txid, err := hex.DecodeString(p.TXID) if err != nil { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("%s could NOT be hex decoded err %s", p.TXID, err)} + return result, fmt.Errorf("%s could NOT be hex decoded err %s", p.TXID, err) } if len(txid) != 32 { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("%s not 64 hex bytes", p.TXID)} + return result, fmt.Errorf("%s not 64 hex bytes", p.TXID) } // if everything is okay, fire the query and convert the result to output format - entry := h.r.w.Get_Payments_TXID(txid) + entry := w.wallet.Get_Payments_TXID(txid) result.Transfer = structures.Transfer_Details{TXID: entry.TXID.String(), Payment_ID: hex.EncodeToString(entry.PaymentID), Height: entry.Height, @@ -63,7 +47,7 @@ func (h Get_Transfer_By_TXID_Handler) ServeJSONRPC(c context.Context, params *fa Unlock_time: entry.Unlock_Time, } if entry.Height == 0 { - return nil, &jsonrpc.Error{Code: -8, Message: fmt.Sprintf("Transaction not found. TXID %s", p.TXID)} + return result, fmt.Errorf("Transaction not found. TXID %s", p.TXID) } for i := range entry.Details.Daddress { @@ -92,5 +76,5 @@ func (h Get_Transfer_By_TXID_Handler) ServeJSONRPC(c context.Context, params *fa } - return nil, &jsonrpc.Error{Code: -8, Message: fmt.Sprintf("Transaction not found. TXID %s", p.TXID)} + return result, fmt.Errorf("Transaction not found. TXID %s", p.TXID) } diff --git a/walletapi/rpc_getaddress.go b/walletapi/rpcserver/rpc_getaddress.go similarity index 75% rename from walletapi/rpc_getaddress.go rename to walletapi/rpcserver/rpc_getaddress.go index f6125e5..8157faf 100644 --- a/walletapi/rpc_getaddress.go +++ b/walletapi/rpcserver/rpc_getaddress.go @@ -14,24 +14,24 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver +import "fmt" import "context" +import "runtime/debug" //import "log" //import "net/http" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - import "github.com/deroproject/derohe/structures" -type GetAddress_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h GetAddress_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { +func (w *WALLET_RPC_APIS) GetAddress(ctx context.Context) (result structures.GetAddress_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() return structures.GetAddress_Result{ - Address: h.r.w.GetAddress().String(), + Address: w.wallet.GetAddress().String(), }, nil } diff --git a/walletapi/rpc_getbalance.go b/walletapi/rpcserver/rpc_getbalance.go similarity index 75% rename from walletapi/rpc_getbalance.go rename to walletapi/rpcserver/rpc_getbalance.go index 45fc5d0..1cf7992 100644 --- a/walletapi/rpc_getbalance.go +++ b/walletapi/rpcserver/rpc_getbalance.go @@ -14,25 +14,21 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver +import "fmt" import "context" - -//import "log" -//import "net/http" - -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - +import "runtime/debug" import "github.com/deroproject/derohe/structures" -type GetBalance_Handler struct { // this has access to the wallet - r *RPCServer -} +func (w *WALLET_RPC_APIS) GetBalance(ctx context.Context) (result structures.GetBalance_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() -func (h GetBalance_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - mature, locked := h.r.w.Get_Balance() + mature, locked := w.wallet.Get_Balance() return structures.GetBalance_Result{ Balance: mature + locked, Unlocked_Balance: mature, diff --git a/walletapi/rpc_getheight.go b/walletapi/rpcserver/rpc_getheight.go similarity index 75% rename from walletapi/rpc_getheight.go rename to walletapi/rpcserver/rpc_getheight.go index bf08e25..13252b3 100644 --- a/walletapi/rpc_getheight.go +++ b/walletapi/rpcserver/rpc_getheight.go @@ -14,24 +14,21 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver +import "fmt" import "context" - -//import "log" -//import "net/http" - -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - +import "runtime/debug" import "github.com/deroproject/derohe/structures" -type GetHeight_Handler struct { // this has access to the wallet - r *RPCServer -} +func (w *WALLET_RPC_APIS) GetHeight(ctx context.Context) (result structures.GetHeight_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() -func (h GetHeight_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { return structures.GetHeight_Result{ - Height: h.r.w.Get_Height(), + Height: w.wallet.Get_Height(), }, nil } diff --git a/walletapi/rpc_gettransfers.go b/walletapi/rpcserver/rpc_gettransfers.go similarity index 61% rename from walletapi/rpc_gettransfers.go rename to walletapi/rpcserver/rpc_gettransfers.go index e41df73..7efe7b8 100644 --- a/walletapi/rpc_gettransfers.go +++ b/walletapi/rpcserver/rpc_gettransfers.go @@ -14,38 +14,24 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver +import "fmt" import "context" import "encoding/hex" - -//import "log" -//import "net/http" - -import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - +import "runtime/debug" import "github.com/deroproject/derohe/structures" -type Get_Transfers_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h Get_Transfers_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - var p structures.Get_Transfers_Params - var result structures.Get_Transfers_Result - //var err error - - if errp := jsonrpc.Unmarshal(params, &p); errp != nil { - rlog.Errorf("Could not parse gettransfers json, err %s\n", errp) - return nil, errp - } +func (w *WALLET_RPC_APIS) GetTransfers(ctx context.Context, p structures.Get_Transfers_Params) (result structures.Get_Transfers_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() //entries := h.r.w.Show_Transfers(p.In, p.In,p.Out,p.Failed, p.Pool,p.Min_Height,p.Max_Height) - in_entries := h.r.w.Show_Transfers(p.In, p.In, false, false, false, false, p.Min_Height, p.Max_Height) - out_entries := h.r.w.Show_Transfers(false, false, p.Out, false, false, false, p.Min_Height, p.Max_Height) + in_entries := w.wallet.Show_Transfers(p.In, p.In, false, false, false, false, p.Min_Height, p.Max_Height) + out_entries := w.wallet.Show_Transfers(false, false, p.Out, false, false, false, p.Min_Height, p.Max_Height) for j := range in_entries { result.In = append(result.In, structures.Transfer_Details{TXID: in_entries[j].TXID.String(), Payment_ID: hex.EncodeToString(in_entries[j].PaymentID), @@ -58,7 +44,7 @@ func (h Get_Transfers_Handler) ServeJSONRPC(c context.Context, params *fastjson. } for j := range out_entries { - transfer := structures.Transfer_Details{TXID: out_entries[j].TXID.String(), + transfer := structures.Transfer_Details{TXID: out_entries[j].TXID.String(), Payment_ID: hex.EncodeToString(out_entries[j].PaymentID), Height: out_entries[j].Height, Amount: out_entries[j].Amount, @@ -66,14 +52,14 @@ func (h Get_Transfers_Handler) ServeJSONRPC(c context.Context, params *fastjson. Type: "out", } - for i := range out_entries[j].Details.Daddress { - transfer.Destinations = append(transfer.Destinations, - structures.Destination{ - Address: out_entries[j].Details.Daddress[i], - Amount: out_entries[j].Details.Amount[i], - }) - } - result.Out = append(result.Out, transfer ) + for i := range out_entries[j].Details.Daddress { + transfer.Destinations = append(transfer.Destinations, + structures.Destination{ + Address: out_entries[j].Details.Daddress[i], + Amount: out_entries[j].Details.Amount[i], + }) + } + result.Out = append(result.Out, transfer) } diff --git a/walletapi/rpc_make_integrated_address.go b/walletapi/rpcserver/rpc_make_integrated_address.go similarity index 61% rename from walletapi/rpc_make_integrated_address.go rename to walletapi/rpcserver/rpc_make_integrated_address.go index 0b8cf94..c688547 100644 --- a/walletapi/rpc_make_integrated_address.go +++ b/walletapi/rpcserver/rpc_make_integrated_address.go @@ -14,58 +14,46 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver import "fmt" import "context" import "encoding/hex" +import "runtime/debug" //import "log" //import "net/http" -import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - import "github.com/deroproject/derohe/structures" -type Make_Integrated_Address_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h Make_Integrated_Address_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - var p structures.Make_Integrated_Address_Params - var result structures.Make_Integrated_Address_Result - //var result structures.Transfer_Result - //var err error - - if errp := jsonrpc.Unmarshal(params, &p); errp != nil { - rlog.Errorf("Could not parse make_integrated_address json, err %s\n", errp) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Could not parse make_integrated_address json, err %s", errp)} - } +func (w *WALLET_RPC_APIS) MakeIntegratedAddress(ctx context.Context, p structures.Make_Integrated_Address_Params) (result structures.Make_Integrated_Address_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() var payment_id []byte if p.Payment_id != "" { payid, err := hex.DecodeString(p.Payment_id) if err != nil { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("%s could NOT be hex decoded err %s", p.Payment_id, err)} + return result, fmt.Errorf("%s could NOT be hex decoded err %s", p.Payment_id, err) } if len(payid) != 8 { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("%s not 16 hex bytes", p.Payment_id)} + return result, fmt.Errorf("%s not 16 hex bytes", p.Payment_id) } payment_id = payid } switch len(payment_id) { case 8: - addr := h.r.w.GetRandomIAddress8() + addr := w.wallet.GetRandomIAddress8() copy(addr.PaymentID, payment_id) result.Integrated_Address = addr.String() result.Payment_id = hex.EncodeToString(payment_id) default: - addr := h.r.w.GetRandomIAddress8() + addr := w.wallet.GetRandomIAddress8() result.Integrated_Address = addr.String() // default return 8 byte encrypted payment ids result.Payment_id = hex.EncodeToString(addr.PaymentID) } diff --git a/walletapi/rpc_query_key.go b/walletapi/rpcserver/rpc_query_key.go similarity index 65% rename from walletapi/rpc_query_key.go rename to walletapi/rpcserver/rpc_query_key.go index 8a613f2..762a801 100644 --- a/walletapi/rpc_query_key.go +++ b/walletapi/rpcserver/rpc_query_key.go @@ -14,47 +14,34 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver import "fmt" -import "strings" import "context" +import "strings" +import "runtime/debug" //import "log" //import "net/http" -import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - import "github.com/deroproject/derohe/structures" -type Query_Key_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h Query_Key_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - var p structures.Query_Key_Params - var result structures.Query_Key_Result - //var result structures.Transfer_Result - //var err error - - if errp := jsonrpc.Unmarshal(params, &p); errp != nil { - rlog.Errorf("Could not parse query key json, err %s\n", errp) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Could not parse query key json, err %s", errp)} - } - +func (w *WALLET_RPC_APIS) QueryKey(ctx context.Context, p structures.Query_Key_Params) (result structures.Query_Key_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() // NOTE: can we give the user the spend key Secret // this is because we are give away the mnemonic which can anyways recreate the full wallet // can we disable mnemonic here switch { case strings.ToLower(p.Key_type) == "mnemonic": - result.Key = h.r.w.GetSeed() + result.Key = w.wallet.GetSeed() //case strings.ToLower(p.Key_type) == "view_key": // result.Key = h.r.w.account.Keys.Viewkey_Secret.String() default: - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Invalid key type, must be mnemonic")} + return result, fmt.Errorf("Invalid key type, must be mnemonic") } return result, nil diff --git a/walletapi/rpc_split_integrated_address.go b/walletapi/rpcserver/rpc_split_integrated_address.go similarity index 55% rename from walletapi/rpc_split_integrated_address.go rename to walletapi/rpcserver/rpc_split_integrated_address.go index da10e6f..b656159 100644 --- a/walletapi/rpc_split_integrated_address.go +++ b/walletapi/rpcserver/rpc_split_integrated_address.go @@ -14,54 +14,41 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver import "fmt" import "context" import "encoding/hex" +import "runtime/debug" //import "log" //import "net/http" -import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" - -//import "github.com/deroproject/derohe/config" -import "github.com/deroproject/derohe/address" import "github.com/deroproject/derohe/structures" +import "github.com/deroproject/derohe/address" -type Split_Integrated_Address_Handler struct { // this has access to the wallet - r *RPCServer -} - -func (h Split_Integrated_Address_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { - - var p structures.Split_Integrated_Address_Params - var result structures.Split_Integrated_Address_Result - //var result structures.Transfer_Result - //var err error - - if errp := jsonrpc.Unmarshal(params, &p); errp != nil { - rlog.Errorf("Could not parse split_integrated_address json, err %s\n", errp) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Could not parse split_integrated_address json, err %s", errp)} - } +func (w *WALLET_RPC_APIS) SplitIntegratedAddress(ctx context.Context, p structures.Split_Integrated_Address_Params) (result structures.Split_Integrated_Address_Result, err error) { + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() if p.Integrated_Address == "" { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Could not find integrated address as parameter")} + return result, fmt.Errorf("Could not find integrated address as parameter") } addr, err := address.NewAddress(p.Integrated_Address) if err != nil { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Error parsing integrated address err %s", err)} + return result, fmt.Errorf("Error parsing integrated address err %s", err) } if !addr.IsDERONetwork() { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("integrated address does not belong to DERO network")} + return result, fmt.Errorf("integrated address does not belong to DERO network") } if !addr.IsIntegratedAddress() { - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("address %s is NOT an integrated address", addr.String())} + return result, fmt.Errorf("address %s is NOT an integrated address", addr.String()) } payment_id := addr.PaymentID diff --git a/walletapi/rpc_transfer.go b/walletapi/rpcserver/rpc_transfer.go similarity index 61% rename from walletapi/rpc_transfer.go rename to walletapi/rpcserver/rpc_transfer.go index b35c3e7..f0f3d78 100644 --- a/walletapi/rpc_transfer.go +++ b/walletapi/rpcserver/rpc_transfer.go @@ -14,56 +14,53 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -package walletapi +package rpcserver import "fmt" +import "sync" import "context" import "encoding/hex" import "encoding/json" +import "runtime/debug" //import "log" //import "net/http" import "github.com/romana/rlog" -import "github.com/intel-go/fastjson" -import "github.com/osamingo/jsonrpc" -import "github.com/deroproject/derohe/globals" -import "github.com/deroproject/derohe/address" import "github.com/deroproject/derohe/structures" +import "github.com/deroproject/derohe/address" +import "github.com/deroproject/derohe/crypto" +import "github.com/deroproject/derohe/globals" -type Transfer_Handler struct { // this has access to the wallet - r *RPCServer -} +var lock sync.Mutex -func (h Transfer_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { +func (w *WALLET_RPC_APIS) Transfer(ctx context.Context, p structures.Transfer_Params) (result structures.Transfer_Result, err error) { - h.r.Lock() - defer h.r.Unlock() - var p structures.Transfer_Params - var result structures.Transfer_Result - var err error + lock.Lock() + defer lock.Unlock() + + defer func() { // safety so if anything wrong happens, we return error + if r := recover(); r != nil { + err = fmt.Errorf("panic occured. stack trace %s", debug.Stack()) + } + }() rlog.Debugf("transfer handler") defer rlog.Debugf("transfer handler finished") - if errp := jsonrpc.Unmarshal(params, &p); err != nil { - rlog.Errorf("Could not parse incoming json, err %s\n", errp) - return nil, errp + if len(p.Destinations) < 1 || p.Mixin != 0 && !crypto.IsPowerOf2(int(p.Mixin)) { + return result, fmt.Errorf("invalid ringsize or destinations") } - //if len(p.Destinations) < 1 || p.Mixin < 4 { - // return nil, jsonrpc.ErrInvalidParams() - //} - rlog.Debugf("Len destinations %d %+v", len(p.Destinations), p) payment_id := p.Payment_ID - if len(payment_id) > 0 && (len(payment_id) == 64 || len(payment_id) == 16) != true { - return nil, jsonrpc.ErrInvalidParams() // we should give invalid payment ID + if len(payment_id) > 0 && len(payment_id) != 16 { + return result, fmt.Errorf("payment id should be 16 hexchars") // we should give invalid payment ID } if _, err := hex.DecodeString(p.Payment_ID); err != nil { - return nil, jsonrpc.ErrInvalidParams() // we should give invalid payment ID + return result, fmt.Errorf("payment id should be 16 hexchars") // we should give invalid payment ID } rlog.Debugf("Payment ID %s", payment_id) @@ -79,8 +76,8 @@ func (h Transfer_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMe for i := range p.Destinations { a, err := globals.ParseValidateAddress(p.Destinations[i].Address) if err != nil { - rlog.Warnf("Parsing address failed %s err %s\n", p.Destinations[i].Address, err) - return nil, jsonrpc.ErrInvalidParams() + rlog.Debugf("Warning Parsing address failed %s err %s\n", p.Destinations[i].Address, err) + return result, fmt.Errorf("Warning Parsing address failed %s err %s\n", p.Destinations[i].Address, err) } address_list = append(address_list, *a) amount_list = append(amount_list, p.Destinations[i].Amount) @@ -88,30 +85,30 @@ func (h Transfer_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMe } fees_per_kb := uint64(0) // fees must be calculated by walletapi - if !h.r.w.GetMode() { // if wallet is in online mode, use the fees, provided by the daemon, else we need to use what is provided by the user + if !w.wallet.GetMode() { // if wallet is in online mode, use the fees, provided by the daemon, else we need to use what is provided by the user - // TODO + return result, fmt.Errorf("Wallet is in offline mode") } - tx, err := h.r.w.Transfer(address_list, amount_list, 0, payment_id, fees_per_kb, p.Mixin, false) + tx, err := w.wallet.Transfer(address_list, amount_list, 0, payment_id, fees_per_kb, p.Mixin, false) if err != nil { rlog.Warnf("Error while building Transaction err %s\n", err) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Error while building Transaction err %s", err)} + return result, err } - rlog.Infof("fees %s \n", globals.FormatMoney(tx.Statement.Fees)) + //rlog.Infof("fees %s \n", globals.FormatMoney(tx.Statement.Fees)) //return nil, jsonrpc.ErrInvalidParams() if p.Do_not_relay == false { // we do not relay the tx, the user must submit it manually // TODO - err = h.r.w.SendTransaction(tx) + err = w.wallet.SendTransaction(tx) if err == nil { - rlog.Infof("Transaction sent successfully. txid = %s", tx.GetHash()) + rlog.Debugf("Transaction sent successfully. txid = %s", tx.GetHash()) } else { - rlog.Warnf("Transaction sending failed txid = %s, err %s", tx.GetHash(), err) - return nil, &jsonrpc.Error{Code: -2, Message: fmt.Sprintf("Transaction sending failed txid = %s, err %s", tx.GetHash(), err)} + rlog.Debugf("Warning Transaction sending failed txid = %s, err %s", tx.GetHash(), err) + return result, fmt.Errorf("Transaction sending failed txid = %s, err %s", tx.GetHash(), err) } } @@ -121,9 +118,9 @@ func (h Transfer_Handler) ServeJSONRPC(c context.Context, params *fastjson.RawMe if p.Get_tx_hex { // request need TX blobs, give them result.Tx_blob = hex.EncodeToString(tx.SerializeHeader()) } - //extract secret key and feed it in here + //extract proof key and feed it in here if p.Get_tx_key { - result.Tx_key = h.r.w.GetTXKey(tx.GetHash()) + result.Tx_key = w.wallet.GetTXKey(tx.GetHash()) } return result, nil } diff --git a/walletapi/rpcserver/rpc_websocket_server.go b/walletapi/rpcserver/rpc_websocket_server.go new file mode 100644 index 0000000..8ddb485 --- /dev/null +++ b/walletapi/rpcserver/rpc_websocket_server.go @@ -0,0 +1,258 @@ +// Copyright 2017-2021 DERO Project. All rights reserved. +// Use of this source code in any form is governed by RESEARCH license. +// license can be found in the LICENSE file. +// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 +// +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package rpcserver + +import "io" +import "net" +import "fmt" +import "net/http" +import "time" +import "sync" +import "sync/atomic" +import "context" +import "strings" +import "runtime/debug" + +import "github.com/deroproject/derohe/config" +import "github.com/deroproject/derohe/globals" +import "github.com/deroproject/derohe/blockchain" +import "github.com/deroproject/derohe/walletapi" +import "github.com/deroproject/derohe/glue/rwc" + +import log "github.com/sirupsen/logrus" +import "github.com/gorilla/websocket" + +import "github.com/creachadair/jrpc2" +import "github.com/creachadair/jrpc2/handler" +import "github.com/creachadair/jrpc2/channel" +import "github.com/creachadair/jrpc2/server" +import "github.com/creachadair/jrpc2/jhttp" + +/* this file implements the rpcserver api, so as wallet and block explorer tools can work without migration */ + +// all components requiring access to blockchain must use , this struct to communicate +// this structure must be update while mutex +type RPCServer struct { + srv *http.Server + mux *http.ServeMux + Exit_Event chan bool // blockchain is shutting down and we must quit ASAP + sync.RWMutex +} + +//var Exit_In_Progress bool +var chain *blockchain.Blockchain +var logger *log.Entry + +var client_connections sync.Map + +var options = &jrpc2.ServerOptions{AllowPush: true} + +func RPCServer_Start(wallet *walletapi.Wallet_Disk) (*RPCServer, error) { + + var err error + var r RPCServer + + _ = err + + logger = globals.Logger.WithFields(log.Fields{"com": "RPC"}) // all components must use this logger + + logger.Infof("RPC/Websocket server starting") + + r.Exit_Event = make(chan bool) + + go r.Run(wallet) + logger.Infof("RPC/Websocket server started") + atomic.AddUint32(&globals.Subsystem_Active, 1) // increment subsystem + + return &r, nil +} + +// shutdown the rpc server component +func (r *RPCServer) RPCServer_Stop() { + r.Lock() + defer r.Unlock() + + close(r.Exit_Event) // send signal to all connections to exit + + if r.srv != nil { + r.srv.Shutdown(context.Background()) // shutdown the server + } + // TODO we must wait for connections to kill themselves + time.Sleep(1 * time.Second) + logger.Infof("RPC Shutdown") + atomic.AddUint32(&globals.Subsystem_Active, ^uint32(0)) // this decrement 1 fom subsystem +} + +// setup handlers +func (r *RPCServer) Run(wallet *walletapi.Wallet_Disk) { + + // create a new mux + r.mux = http.NewServeMux() + + default_address := "127.0.0.1:" + fmt.Sprintf("%d", config.Mainnet.Wallet_RPC_Default_Port) + if !globals.IsMainnet() { + default_address = "127.0.0.1:" + fmt.Sprintf("%d", config.Testnet.Wallet_RPC_Default_Port) + } + + if _, ok := globals.Arguments["--rpc-bind"]; ok && globals.Arguments["--rpc-bind"] != nil { + addr, err := net.ResolveTCPAddr("tcp", globals.Arguments["--rpc-bind"].(string)) + if err != nil { + logger.Warnf("--rpc-bind address is invalid, err = %s", err) + } else { + if addr.Port == 0 { + logger.Infof("RPC server is disabled, No ports will be opened for RPC") + return + } else { + default_address = addr.String() + } + } + } + + logger.Infof("RPC will listen on %s", default_address) + r.Lock() + r.srv = &http.Server{Addr: default_address, Handler: r.mux} + r.Unlock() + + r.mux.HandleFunc("/json_rpc", translate_http_to_jsonrpc_and_vice_versa) + r.mux.HandleFunc("/ws", ws_handler) + r.mux.HandleFunc("/", hello) + //r.mux.Handle("/json_rpc", mr) + + // handle nasty http requests + //r.mux.HandleFunc("/getheight", getheight) + + //if DEBUG_MODE { + // r.mux.HandleFunc("/debug/pprof/", pprof.Index) + + // Register pprof handlers individually if required + /* r.mux.HandleFunc("/debug/pprof/", pprof.Index) + r.mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) + r.mux.HandleFunc("/debug/pprof/profile", pprof.Profile) + r.mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) + r.mux.HandleFunc("/debug/pprof/trace", pprof.Trace) + */ + + /* + // Register pprof handlers individually if required + r.mux.HandleFunc("/cdebug/pprof/", pprof.Index) + r.mux.HandleFunc("/cdebug/pprof/cmdline", pprof.Cmdline) + r.mux.HandleFunc("/cdebug/pprof/profile", pprof.Profile) + r.mux.HandleFunc("/cdebug/pprof/symbol", pprof.Symbol) + r.mux.HandleFunc("/cdebug/pprof/trace", pprof.Trace) + */ + + // register metrics handler + // r.mux.HandleFunc("/metrics", prometheus.InstrumentHandler("dero", promhttp.HandlerFor(metrics.Registry, promhttp.HandlerOpts{}))) + + //} + + //r.mux.HandleFunc("/json_rpc/debug", mr.ServeDebug) + + wallet_apis.wallet = wallet + if err := r.srv.ListenAndServe(); err != http.ErrServerClosed { + logger.Warnf("ERR listening to address err %s", err) + } + +} + +func hello(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "DERO BLOCKCHAIN Hello world!") +} + +var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} // use default options + +func ws_handler(w http.ResponseWriter, r *http.Request) { + + var ws_server *jrpc2.Server + defer func() { + + // safety so if anything wrong happens, verification fails + if r := recover(); r != nil { + logger.Warnf("Recovered while processing websocket request, Stack trace below ") + logger.Warnf("Stack trace \n%s", debug.Stack()) + } + if ws_server != nil { + client_connections.Delete(ws_server) + } + + }() + + c, err := upgrader.Upgrade(w, r, nil) + if err != nil { + log.Print("upgrade:", err) + return + } + defer c.Close() + + input_output := rwc.New(c) + ws_server = jrpc2.NewServer(assigner, options).Start(channel.RawJSON(input_output, input_output)) + client_connections.Store(ws_server, 1) + ws_server.Wait() +} + +var assigner = handler.ServiceMap{ + "WALLET": handler.NewService(WALLET_RPC_APIS{}), + "DERO": handler.NewService(DERO_RPC_APIS{}), +} + +type WALLET_RPC_APIS struct { + wallet *walletapi.Wallet_Disk +} // exports daemon status and other RPC apis + +func (WALLET_RPC_APIS) Echo(ctx context.Context, args []string) string { + return "WALLET " + strings.Join(args, " ") +} + +type DERO_RPC_APIS struct{} // exports DERO specific apis, such as transaction + +// used to verify whether the connection is alive +func (DERO_RPC_APIS) Ping(ctx context.Context) string { + return "Pong " +} + +func (DERO_RPC_APIS) Echo(ctx context.Context, args []string) string { + return "DERO " + strings.Join(args, " ") +} + +//var internal_server = server.NewLocal(assigner,nil) // Use DERO.GetInfo names +var internal_server = server.NewLocal(historical_apis, nil) // uses traditional "getinfo" for compatibility reasons +// Bridge HTTP to the JSON-RPC server. +var bridge = jhttp.NewBridge(internal_server.Client) + +var wallet_apis WALLET_RPC_APIS +var dero_apis DERO_RPC_APIS + +var historical_apis = handler.Map{"getaddress": handler.New(wallet_apis.GetAddress), + "getbalance": handler.New(wallet_apis.GetBalance), + "get_bulk_payments": handler.New(wallet_apis.GetBulkPayments), + "getheight": handler.New(wallet_apis.GetHeight), + "get_transfer_by_txid": handler.New(wallet_apis.GetTransferbyTXID), + "get_transfers": handler.New(wallet_apis.GetTransfers), + "make_integrated_address": handler.New(wallet_apis.MakeIntegratedAddress), + "split_integrated_address": handler.New(wallet_apis.SplitIntegratedAddress), + "query_key": handler.New(wallet_apis.QueryKey), + "transfer": handler.New(wallet_apis.Transfer), + "transfer_split": handler.New(wallet_apis.Transfer), + // "getblockcount": handler.New(wallet_apis.GetBlockCount), + // "getlastblockheader": handler.New(wallet_apis.GetLastBlockHeader), + // "getblocktemplate": handler.New(wallet_apis.GetBlockTemplate), + // "getencryptedbalance": handler.New(wallet_apis.GetEncryptedBalance) +} + +func translate_http_to_jsonrpc_and_vice_versa(w http.ResponseWriter, r *http.Request) { + bridge.ServeHTTP(w, r) +} diff --git a/walletapi/wallet.go b/walletapi/wallet.go index d1fd2f2..5bfccf2 100644 --- a/walletapi/wallet.go +++ b/walletapi/wallet.go @@ -17,7 +17,6 @@ package walletapi import "fmt" -import "net" import "sort" import "sync" import "time" @@ -50,7 +49,7 @@ type _Keys struct { Public *crypto.Point `json:"public"` } -var Balance_lookup_table *LookupTable +var Balance_lookup_table *LookupTable type Account struct { Keys _Keys `json:"keys"` @@ -71,6 +70,8 @@ type Account struct { RingMembers map[string]int64 `json:"ring_members"` // ring members + Pool Wallet_Pool // wallet pool + sync.Mutex // syncronise modifications to this structure } @@ -99,7 +100,7 @@ type Entry struct { // add a entry in the suitable place // this is always single threaded -func (w *Wallet) InsertReplace(e Entry) { +func (w *Wallet_Memory) InsertReplace(e Entry) { i := sort.Search(len(w.account.Entries), func(j int) bool { return w.account.Entries[j].TopoHeight >= e.TopoHeight && w.account.Entries[j].TransactionPos >= e.TransactionPos @@ -161,12 +162,12 @@ func Generate_Account_From_Seed(Seed *crypto.BNRed) (user *Account, err error) { } // convert key to seed using language -func (w *Wallet) GetSeed() (str string) { +func (w *Wallet_Memory) GetSeed() (str string) { return mnemonics.Key_To_Words(w.account.Keys.Secret.BigInt(), w.account.SeedLanguage) } // convert key to seed using language -func (w *Wallet) GetSeedinLanguage(lang string) (str string) { +func (w *Wallet_Memory) GetSeedinLanguage(lang string) (str string) { return mnemonics.Key_To_Words(w.account.Keys.Secret.BigInt(), lang) } @@ -176,14 +177,14 @@ func (account *Account) GetAddress() (addr address.Address) { } // convert a user account to address -func (w *Wallet) GetAddress() (addr address.Address) { +func (w *Wallet_Memory) GetAddress() (addr address.Address) { addr = w.account.GetAddress() addr.Mainnet = w.account.mainnet return addr } // get a random integrated address -func (w *Wallet) GetRandomIAddress8() (addr address.Address) { +func (w *Wallet_Memory) GetRandomIAddress8() (addr address.Address) { addr = w.GetAddress() // setup random 8 bytes of payment ID, it must be from non-deterministic RNG namely crypto random @@ -193,7 +194,7 @@ func (w *Wallet) GetRandomIAddress8() (addr address.Address) { return } -func (w *Wallet) Get_Balance_Rescan() (mature_balance uint64, locked_balance uint64) { +func (w *Wallet_Memory) Get_Balance_Rescan() (mature_balance uint64, locked_balance uint64) { return w.Get_Balance() } @@ -201,7 +202,7 @@ func (w *Wallet) Get_Balance_Rescan() (mature_balance uint64, locked_balance uin // offline wallets may get this wrong, since they may not have latest data // -func (w *Wallet) Get_Balance() (mature_balance uint64, locked_balance uint64) { +func (w *Wallet_Memory) Get_Balance() (mature_balance uint64, locked_balance uint64) { return w.account.Balance_Mature, 0 } @@ -213,7 +214,7 @@ func (w *Wallet) Get_Balance() (mature_balance uint64, locked_balance uint64) { //TODO currently we do not track POOL at all any where ( except while building tx) // if payment_id is true, only entries with payment ids are returned // min_height/max height represent topoheight -func (w *Wallet) Show_Transfers(available bool, in bool, out bool, pool bool, failed bool, payment_id bool, min_height, max_height uint64) (entries []Entry) { +func (w *Wallet_Memory) Show_Transfers(available bool, in bool, out bool, pool bool, failed bool, payment_id bool, min_height, max_height uint64) (entries []Entry) { // dero_first_block_time := time.Unix(1512432000, 0) //Tuesday, December 5, 2017 12:00:00 AM @@ -249,7 +250,7 @@ func (w *Wallet) Show_Transfers(available bool, in bool, out bool, pool bool, fa // gets all the payments done to specific payment ID and filtered by specific block height // we do need better structures -func (w *Wallet) Get_Payments_Payment_ID(payid []byte, min_height uint64) (entries []Entry) { +func (w *Wallet_Memory) Get_Payments_Payment_ID(payid []byte, min_height uint64) (entries []Entry) { for _, e := range w.account.Entries { if e.Height >= min_height { if bytes.Compare(payid, e.PaymentID[:]) == 0 { @@ -263,8 +264,8 @@ func (w *Wallet) Get_Payments_Payment_ID(payid []byte, min_height uint64) (entri } // return all payments within a tx there can be only 1 entry -// NOTE: -func (w *Wallet) Get_Payments_TXID(txid []byte) (entry Entry) { +// NOTE: what about multiple payments +func (w *Wallet_Memory) Get_Payments_TXID(txid []byte) (entry Entry) { for _, e := range w.account.Entries { if bytes.Compare(txid, e.TXID[:]) == 0 { return e @@ -274,113 +275,70 @@ func (w *Wallet) Get_Payments_TXID(txid []byte) (entry Entry) { return } -// get the unlocked balance ( amounts which are mature and can be spent at this time ) -// offline wallets may get this wrong, since they may not have latest data -// TODO: for offline wallets, we must make all balance as mature -// -func (w *Wallet) Start_RPC_Server(address string) (err error) { - w.Lock() - defer w.Unlock() - - tcpAddr, err := net.ResolveTCPAddr("tcp", address) - if err != nil { - return - } - - w.rpcserver, err = RPCServer_Start(w, tcpAddr.String()) - if err != nil { - w.rpcserver = nil - } - - return -} - -func (w *Wallet) Stop_RPC_Server() { - w.Lock() - defer w.Unlock() - - if w.rpcserver != nil { - w.rpcserver.RPCServer_Stop() - w.rpcserver = nil // remover reference - } - - return -} - // delete most of the data and prepare for rescan -func (w *Wallet) Clean() { +func (w *Wallet_Memory) Clean() { w.account.Entries = w.account.Entries[:0] w.account.Balance_Result.Data = "" } // return height of wallet -func (w *Wallet) Get_Height() uint64 { +func (w *Wallet_Memory) Get_Height() uint64 { return uint64(w.account.Balance_Result.Height) } // return topoheight of wallet -func (w *Wallet) Get_TopoHeight() int64 { +func (w *Wallet_Memory) Get_TopoHeight() int64 { return w.account.Balance_Result.Topoheight } -func (w *Wallet) Get_Daemon_Height() uint64 { - w.Lock() - defer w.Unlock() - +func (w *Wallet_Memory) Get_Daemon_Height() uint64 { return w.Daemon_Height } -func (w *Wallet) Get_Registration_TopoHeight() int64 { +// return topoheight of darmon +func (w *Wallet_Memory) Get_Daemon_TopoHeight() int64 { + return w.Daemon_TopoHeight +} + +func (w *Wallet_Memory) Get_Registration_TopoHeight() int64 { return w.account.Balance_Result.Registration } -func (w *Wallet) Get_Keys() _Keys { +func (w *Wallet_Memory) Get_Keys() _Keys { return w.account.Keys } // by default a wallet opens in Offline Mode // however, if the wallet is in online mode, it can be made offline instantly using this -func (w *Wallet) SetOfflineMode() bool { - w.Lock() - defer w.Unlock() - +func (w *Wallet_Memory) SetOfflineMode() bool { current_mode := w.wallet_online_mode w.wallet_online_mode = false return current_mode } -func (w *Wallet) SetNetwork(mainnet bool) bool { +func (w *Wallet_Memory) SetNetwork(mainnet bool) bool { w.account.mainnet = mainnet return w.account.mainnet } -func (w *Wallet) GetNetwork() bool { +func (w *Wallet_Memory) GetNetwork() bool { return w.account.mainnet } // return current mode -func (w *Wallet) GetMode() bool { - w.RLock() - defer w.RUnlock() - +func (w *Wallet_Memory) GetMode() bool { return w.wallet_online_mode } // use the endpoint set by the program -func (w *Wallet) SetDaemonAddress(endpoint string) string { - w.Lock() - defer w.Unlock() - +func (w *Wallet_Memory) SetDaemonAddress(endpoint string) string { w.Daemon_Endpoint = endpoint return w.Daemon_Endpoint } // by default a wallet opens in Offline Mode // however, It can be made online by calling this -func (w *Wallet) SetOnlineMode() bool { - w.Lock() - defer w.Unlock() - +func (w *Wallet_Memory) SetOnlineMode() bool { current_mode := w.wallet_online_mode w.wallet_online_mode = true @@ -392,10 +350,8 @@ func (w *Wallet) SetOnlineMode() bool { // by default a wallet opens in Offline Mode // however, It can be made online by calling this -func (w *Wallet) SetRingSize(ringsize int) int { +func (w *Wallet_Memory) SetRingSize(ringsize int) int { defer w.Save_Wallet() // save wallet - w.Lock() - defer w.Unlock() if ringsize >= 2 && ringsize <= 128 { //reasonable limits for mixin, atleastt for now, network should bump it to 13 on next HF @@ -408,9 +364,7 @@ func (w *Wallet) SetRingSize(ringsize int) int { // by default a wallet opens in Offline Mode // however, It can be made online by calling this -func (w *Wallet) GetRingSize() int { - w.Lock() - defer w.Unlock() +func (w *Wallet_Memory) GetRingSize() int { if w.account.Ringsize < 2 { return 2 } @@ -418,11 +372,9 @@ func (w *Wallet) GetRingSize() int { } // sets a fee multiplier -func (w *Wallet) SetFeeMultiplier(x float32) float32 { +func (w *Wallet_Memory) SetFeeMultiplier(x float32) float32 { defer w.Save_Wallet() // save wallet - w.Lock() - defer w.Unlock() - if x < 1.0 { // fee cannot be less than 1.0, base fees + if x < 1.0 { // fee cannot be less than 1.0, base fees w.account.FeesMultiplier = 2.0 } else { w.account.FeesMultiplier = x @@ -431,9 +383,7 @@ func (w *Wallet) SetFeeMultiplier(x float32) float32 { } // gets current fee multiplier -func (w *Wallet) GetFeeMultiplier() float32 { - w.Lock() - defer w.Unlock() +func (w *Wallet_Memory) GetFeeMultiplier() float32 { if w.account.FeesMultiplier < 1.0 { return 1.0 } @@ -441,7 +391,7 @@ func (w *Wallet) GetFeeMultiplier() float32 { } // get fees multiplied by multiplier -func (w *Wallet) getfees(txfee uint64) uint64 { +func (w *Wallet_Memory) getfees(txfee uint64) uint64 { multiplier := w.account.FeesMultiplier if multiplier < 1.0 { multiplier = 2.0 @@ -450,10 +400,8 @@ func (w *Wallet) getfees(txfee uint64) uint64 { } // Ability to change seed lanaguage -func (w *Wallet) SetSeedLanguage(language string) string { +func (w *Wallet_Memory) SetSeedLanguage(language string) string { defer w.Save_Wallet() // save wallet - w.Lock() - defer w.Unlock() language_list := mnemonics.Language_List() for i := range language_list { @@ -465,9 +413,7 @@ func (w *Wallet) SetSeedLanguage(language string) string { } // retrieve current seed language -func (w *Wallet) GetSeedLanguage() string { - w.Lock() - defer w.Unlock() +func (w *Wallet_Memory) GetSeedLanguage() string { if w.account.SeedLanguage == "" { // default is English return "English" } @@ -475,7 +421,7 @@ func (w *Wallet) GetSeedLanguage() string { } // retrieve secret key for any tx we may have created -func (w *Wallet) GetRegistrationTX() *transaction.Transaction { +func (w *Wallet_Memory) GetRegistrationTX() *transaction.Transaction { var tx transaction.Transaction tx.Version = 1 tx.TransactionType = transaction.REGISTRATION @@ -493,7 +439,7 @@ func (w *Wallet) GetRegistrationTX() *transaction.Transaction { } // this basically does a Schnorr Signature on random information for registration -func (w *Wallet) sign() (c, s *big.Int) { +func (w *Wallet_Memory) sign() (c, s *big.Int) { var tmppoint bn256.G1 tmpsecret := crypto.RandomScalar() @@ -510,7 +456,7 @@ func (w *Wallet) sign() (c, s *big.Int) { } // retrieve secret key for any tx we may have created -func (w *Wallet) GetTXKey(txhash crypto.Hash) string { +func (w *Wallet_Memory) GetTXKey(txhash crypto.Hash) string { for _, e := range w.account.Entries { if !e.Coinbase && !e.Incoming && e.TXID == txhash { return e.Proof @@ -519,20 +465,3 @@ func (w *Wallet) GetTXKey(txhash crypto.Hash) string { return "" } - -// we need better names for functions -func (w *Wallet) GetTXOutDetails(txhash crypto.Hash) (details structures.Outgoing_Transfer_Details) { - - panic("not implemented") - /* - data_bytes, err := w.load_key_value(BLOCKCHAIN_UNIVERSE, []byte(TX_OUT_DETAILS_BUCKET), txhash[:]) - if err != nil { - return - } - - if len(data_bytes) > 10 { - json.Unmarshal(data_bytes, &details) - } - */ - return -} diff --git a/walletapi/wallet_pool.go b/walletapi/wallet_pool.go new file mode 100644 index 0000000..59ec617 --- /dev/null +++ b/walletapi/wallet_pool.go @@ -0,0 +1,73 @@ +// Copyright 2017-2021 DERO Project. All rights reserved. +// Use of this source code in any form is governed by RESEARCH license. +// license can be found in the LICENSE file. +// GPG: 0F39 E425 8C65 3947 702A 8234 08B2 0360 A03A 9DE8 +// +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package walletapi + +// the objective of this file is to implememt a pool which sends and retries transactions until they are accepted by the chain + +//import "fmt" + +//import "encoding/binary" +//import "encoding/hex" + +//import "encoding/json" + +//import "github.com/romana/rlog" + +//import "github.com/vmihailenco/msgpack" + +//import "github.com/deroproject/derohe/config" +//import "github.com/deroproject/derohe/crypto" + +//import "github.com/deroproject/derohe/crypto/ringct" +import "github.com/deroproject/derohe/transaction" + +//import "github.com/deroproject/derohe/globals" +import "github.com/deroproject/derohe/address" + +//import "github.com/deroproject/derohe/structures" +//import "github.com/deroproject/derohe/blockchain/inputmaturity" +//import "github.com/deroproject/derohe/crypto/bn256" + +type Wallet_Pool []Wallet_Pool_Entry + +type Wallet_Pool_Entry struct { + Addr []address.Address + Amount []uint64 + RingSize uint64 + Transfer_Everything bool + Trigger_Height int64 +} + +// send amount to specific addresses +func (w *Wallet_Memory) PoolTransfer(addr []address.Address, amount []uint64, unlock_time uint64, payment_id_hex string, fees_per_kb uint64, ringsize uint64, transfer_all bool) (tx *transaction.Transaction, err error) { + + // var transfer_details structures.Outgoing_Transfer_Details + + var entry Wallet_Pool_Entry + + for i := range addr { + entry.Addr = append(entry.Addr, addr[i]) + entry.Amount = append(entry.Amount, amount[i]) + + } + entry.RingSize = ringsize + entry.Transfer_Everything = transfer_all + + w.account.Pool = append(w.account.Pool, entry) + + return +} diff --git a/walletapi/wallet_transfer.go b/walletapi/wallet_transfer.go index b0948c9..3519891 100644 --- a/walletapi/wallet_transfer.go +++ b/walletapi/wallet_transfer.go @@ -45,7 +45,7 @@ import "github.com/deroproject/derohe/address" import "github.com/deroproject/derohe/crypto/bn256" // send amount to specific addresses -func (w *Wallet) Transfer(addr []address.Address, amount []uint64, unlock_time uint64, payment_id_hex string, fees_per_kb uint64, ringsize uint64, transfer_all bool) (tx *transaction.Transaction, err error) { +func (w *Wallet_Memory) Transfer(addr []address.Address, amount []uint64, unlock_time uint64, payment_id_hex string, fees_per_kb uint64, ringsize uint64, transfer_all bool) (tx *transaction.Transaction, err error) { // var transfer_details structures.Outgoing_Transfer_Details w.transfer_mutex.Lock() @@ -150,6 +150,14 @@ func (w *Wallet) Transfer(addr []address.Address, amount []uint64, unlock_time u return } + WaitNewHeightBlock() // wait till a new block at new height is found + // due to this we weill dispatch a new tx immediate after a block is found for better propagation + + self_e, err = w.GetEncryptedBalance("", w.GetAddress().String()) + if err != nil { + return + } + if w.account.Balance_Result.Data != previous { // wallet is stale, we need to update our balance w.DecodeEncryptedBalance() // try to decode balance }