├── CHANG ├── COPYING ├── COPYING.LESSER ├── LICENSE ├── Makefile ├── README.md ├── accounts ├── abi │ ├── abi.go │ ├── abi_test.go │ ├── argument.go │ ├── bind │ │ ├── auth.go │ │ ├── backend.go │ │ ├── backends │ │ │ └── simulated.go │ │ ├── base.go │ │ ├── bind.go │ │ ├── bind_test.go │ │ ├── template.go │ │ ├── topics.go │ │ ├── util.go │ │ └── util_test.go │ ├── doc.go │ ├── error.go │ ├── event.go │ ├── event_test.go │ ├── method.go │ ├── numbers.go │ ├── numbers_test.go │ ├── pack.go │ ├── pack_test.go │ ├── reflect.go │ ├── type.go │ ├── type_test.go │ ├── unpack.go │ └── unpack_test.go ├── accounts.go ├── errors.go ├── hd.go ├── hd_test.go ├── keystore │ ├── account_cache.go │ ├── account_cache_test.go │ ├── file_cache.go │ ├── key.go │ ├── keystore.go │ ├── keystore_passphrase.go │ ├── keystore_passphrase_test.go │ ├── keystore_plain.go │ ├── keystore_plain_test.go │ ├── keystore_test.go │ ├── keystore_wallet.go │ ├── presale.go │ ├── testdata │ │ ├── dupes │ │ │ ├── 1 │ │ │ ├── 2 │ │ │ └── foo │ │ ├── keystore │ │ │ ├── .hiddenfile │ │ │ ├── README │ │ │ ├── UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8 │ │ │ ├── aaa │ │ │ ├── empty │ │ │ ├── foo │ │ │ │ └── fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e │ │ │ ├── garbage │ │ │ ├── no-address │ │ │ ├── zero │ │ │ └── zzz │ │ ├── v1 │ │ │ └── cb61d5a9c4896fb9658090b597ef0e7be6f7b67e │ │ │ │ └── cb61d5a9c4896fb9658090b597ef0e7be6f7b67e │ │ ├── v1_test_vector.json │ │ ├── v3_test_vector.json │ │ └── very-light-scrypt.json │ ├── watch.go │ └── watch_fallback.go ├── manager.go ├── url.go └── usbwallet │ ├── hub.go │ ├── internal │ └── trezor │ │ ├── messages.pb.go │ │ ├── messages.proto │ │ ├── trezor.go │ │ ├── types.pb.go │ │ └── types.proto │ ├── ledger.go │ ├── trezor.go │ └── wallet.go ├── api.go ├── api_test.go ├── app ├── app.go ├── mock.go ├── mock_test.go └── test.sh ├── bftcosi ├── bftcosi.go ├── bftcosi_test.go └── packets.go ├── blockchain ├── blkparser │ ├── block.go │ ├── blockchain.go │ ├── tx.go │ └── utils.go ├── common.go ├── common.pb.go ├── common.proto ├── hashid.go ├── keyblock.go ├── messg.go ├── parser.go ├── proof.go ├── proof_test.go ├── transactionlist.go └── txblock.go ├── common ├── big.go ├── bitutil │ ├── bitutil.go │ ├── bitutil_test.go │ ├── compress.go │ ├── compress_fuzz.go │ └── compress_test.go ├── bytes.go ├── bytes_test.go ├── compiler │ ├── solidity.go │ └── solidity_test.go ├── debug.go ├── fdlimit │ ├── fdlimit_freebsd.go │ ├── fdlimit_test.go │ ├── fdlimit_unix.go │ └── fdlimit_windows.go ├── format.go ├── hexutil │ ├── hexutil.go │ ├── hexutil_test.go │ ├── json.go │ ├── json_example_test.go │ └── json_test.go ├── main_test.go ├── math │ ├── big.go │ ├── big_test.go │ ├── integer.go │ └── integer_test.go ├── mclock │ └── mclock.go ├── number │ ├── int.go │ └── uint_test.go ├── path.go ├── size.go ├── size_test.go ├── test_utils.go ├── types.go ├── types_template.go └── types_test.go ├── conode ├── README.md ├── conode.go ├── conode_test.go ├── run_conode.sh └── test.sh ├── core ├── key_block_validator.go ├── key_blockchain.go └── key_headerchain.go ├── cosi ├── README.md ├── check │ └── check.go ├── client.go ├── cosi.go ├── cosi_test.go ├── crypto │ ├── README.md │ ├── cosi.go │ └── cosi_test.go ├── protocol │ ├── cosi.go │ ├── cosi_test.go │ └── packets.go ├── server.go ├── server_test.go ├── service │ ├── api.go │ ├── cosi.go │ ├── cosi.proto │ └── cosi_test.go ├── simulation │ ├── cosi.toml │ ├── cosi_test.go │ ├── cosi_verification.toml │ ├── fd_test.go │ ├── fd_unix_test.go │ ├── protocol.go │ ├── simul.go │ ├── simul_test.go │ └── simulation.go └── test.sh ├── crypto ├── bn256 │ ├── bn256_fast.go │ ├── bn256_fuzz.go │ ├── bn256_slow.go │ ├── cloudflare │ │ ├── bn256.go │ │ ├── bn256_test.go │ │ ├── constants.go │ │ ├── curve.go │ │ ├── example_test.go │ │ ├── gfp.go │ │ ├── gfp12.go │ │ ├── gfp2.go │ │ ├── gfp6.go │ │ ├── gfp_amd64.s │ │ ├── gfp_arm64.s │ │ ├── gfp_decl.go │ │ ├── gfp_generic.go │ │ ├── gfp_test.go │ │ ├── lattice.go │ │ ├── lattice_test.go │ │ ├── main_test.go │ │ ├── mul_amd64.h │ │ ├── mul_arm64.h │ │ ├── mul_bmi2_amd64.h │ │ ├── optate.go │ │ └── twist.go │ └── google │ │ ├── bn256.go │ │ ├── bn256_test.go │ │ ├── constants.go │ │ ├── curve.go │ │ ├── example_test.go │ │ ├── gfp12.go │ │ ├── gfp2.go │ │ ├── gfp6.go │ │ ├── main_test.go │ │ ├── optate.go │ │ └── twist.go ├── crypto.go ├── crypto_test.go ├── ecies │ ├── .gitignore │ ├── LICENSE │ ├── README │ ├── ecies.go │ ├── ecies_test.go │ └── params.go ├── randentropy │ └── rand_entropy.go ├── secp256k1 │ ├── .gitignore │ ├── curve.go │ ├── ext.h │ ├── libsecp256k1 │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── COPYING │ │ ├── Makefile.am │ │ ├── README.md │ │ ├── TODO │ │ ├── autogen.sh │ │ ├── build-aux │ │ │ └── m4 │ │ │ │ ├── ax_jni_include_dir.m4 │ │ │ │ ├── ax_prog_cc_for_build.m4 │ │ │ │ └── bitcoin_secp.m4 │ │ ├── configure.ac │ │ ├── contrib │ │ │ ├── lax_der_parsing.c │ │ │ ├── lax_der_parsing.h │ │ │ ├── lax_der_privatekey_parsing.c │ │ │ └── lax_der_privatekey_parsing.h │ │ ├── include │ │ │ ├── secp256k1.h │ │ │ ├── secp256k1_ecdh.h │ │ │ └── secp256k1_recovery.h │ │ ├── libsecp256k1.pc.in │ │ ├── obj │ │ │ └── .gitignore │ │ ├── sage │ │ │ ├── group_prover.sage │ │ │ ├── secp256k1.sage │ │ │ └── weierstrass_prover.sage │ │ └── src │ │ │ ├── asm │ │ │ └── field_10x26_arm.s │ │ │ ├── basic-config.h │ │ │ ├── bench.h │ │ │ ├── bench_ecdh.c │ │ │ ├── bench_internal.c │ │ │ ├── bench_recover.c │ │ │ ├── bench_schnorr_verify.c │ │ │ ├── bench_sign.c │ │ │ ├── bench_verify.c │ │ │ ├── ecdsa.h │ │ │ ├── ecdsa_impl.h │ │ │ ├── eckey.h │ │ │ ├── eckey_impl.h │ │ │ ├── ecmult.h │ │ │ ├── ecmult_const.h │ │ │ ├── ecmult_const_impl.h │ │ │ ├── ecmult_gen.h │ │ │ ├── ecmult_gen_impl.h │ │ │ ├── ecmult_impl.h │ │ │ ├── field.h │ │ │ ├── field_10x26.h │ │ │ ├── field_10x26_impl.h │ │ │ ├── field_5x52.h │ │ │ ├── field_5x52_asm_impl.h │ │ │ ├── field_5x52_impl.h │ │ │ ├── field_5x52_int128_impl.h │ │ │ ├── field_impl.h │ │ │ ├── gen_context.c │ │ │ ├── group.h │ │ │ ├── group_impl.h │ │ │ ├── hash.h │ │ │ ├── hash_impl.h │ │ │ ├── java │ │ │ ├── org │ │ │ │ └── bitcoin │ │ │ │ │ ├── NativeSecp256k1.java │ │ │ │ │ ├── NativeSecp256k1Test.java │ │ │ │ │ ├── NativeSecp256k1Util.java │ │ │ │ │ └── Secp256k1Context.java │ │ │ ├── org_bitcoin_NativeSecp256k1.c │ │ │ ├── org_bitcoin_NativeSecp256k1.h │ │ │ ├── org_bitcoin_Secp256k1Context.c │ │ │ └── org_bitcoin_Secp256k1Context.h │ │ │ ├── modules │ │ │ ├── ecdh │ │ │ │ ├── Makefile.am.include │ │ │ │ ├── main_impl.h │ │ │ │ └── tests_impl.h │ │ │ └── recovery │ │ │ │ ├── Makefile.am.include │ │ │ │ ├── main_impl.h │ │ │ │ └── tests_impl.h │ │ │ ├── num.h │ │ │ ├── num_gmp.h │ │ │ ├── num_gmp_impl.h │ │ │ ├── num_impl.h │ │ │ ├── scalar.h │ │ │ ├── scalar_4x64.h │ │ │ ├── scalar_4x64_impl.h │ │ │ ├── scalar_8x32.h │ │ │ ├── scalar_8x32_impl.h │ │ │ ├── scalar_impl.h │ │ │ ├── scalar_low.h │ │ │ ├── scalar_low_impl.h │ │ │ ├── secp256k1.c │ │ │ ├── testrand.h │ │ │ ├── testrand_impl.h │ │ │ ├── tests.c │ │ │ ├── tests_exhaustive.c │ │ │ └── util.h │ ├── panic_cb.go │ ├── secp256.go │ └── secp256_test.go ├── sha3 │ ├── LICENSE │ ├── PATENTS │ ├── doc.go │ ├── hashes.go │ ├── keccakf.go │ ├── keccakf_amd64.go │ ├── keccakf_amd64.s │ ├── register.go │ ├── sha3.go │ ├── sha3_test.go │ ├── shake.go │ ├── testdata │ │ └── keccakKats.json.deflate │ ├── xor.go │ ├── xor_generic.go │ └── xor_unaligned.go ├── signature_cgo.go ├── signature_nocgo.go └── signature_test.go ├── cypherium ├── client.go ├── cypherium.go ├── cypherium_test.go ├── server.go └── struct.go ├── db ├── .gitignore ├── database.go ├── database_test.go ├── interface.go └── memory_database.go ├── event ├── event.go ├── event_test.go ├── example_feed_test.go ├── example_scope_test.go ├── example_subscription_test.go ├── example_test.go ├── feed.go ├── feed_test.go ├── filter │ ├── filter.go │ ├── filter_test.go │ └── generic_filter.go ├── subscription.go └── subscription_test.go ├── html ├── README.md ├── css │ ├── custom.css │ ├── font-awesome.min.css │ ├── ie8.css │ ├── ie9.css │ ├── images │ │ └── overlay.png │ ├── main.css │ ├── noscript.css │ └── progress.css ├── fonts │ ├── FontAwesome.otf │ ├── fontawesome-webfont.eot │ ├── fontawesome-webfont.svg │ ├── fontawesome-webfont.ttf │ ├── fontawesome-webfont.woff │ └── fontawesome-webfont.woff2 ├── images │ ├── avatar.jpg │ ├── bg-old.jpg │ └── bg.jpg ├── index.html ├── js │ ├── PIE.htc │ ├── bundle.js │ ├── html5shiv.js │ ├── jquery.min.js │ ├── moment.min.js │ ├── protobuf.min.js │ ├── respond.min.js │ ├── topl.min.js │ └── uuid.min.js └── src │ ├── Makefile │ ├── build.js │ ├── build_proto.js │ ├── cothority-protobuf.js │ ├── cothority-protobuf.test.js │ ├── index.js │ ├── index.test.js │ ├── models │ ├── cothority_template.proto │ ├── root.js │ ├── roster.proto │ ├── server-identity.proto │ ├── skeleton.js │ └── status.proto │ └── package.json ├── log ├── CONTRIBUTORS ├── LICENSE ├── README.md ├── README_ETHEREUM.md ├── doc.go ├── format.go ├── handler.go ├── handler_glog.go ├── handler_go13.go ├── handler_go14.go ├── logger.go ├── root.go ├── syslog.go └── term │ ├── LICENSE │ ├── terminal_appengine.go │ ├── terminal_darwin.go │ ├── terminal_freebsd.go │ ├── terminal_linux.go │ ├── terminal_netbsd.go │ ├── terminal_notwindows.go │ ├── terminal_openbsd.go │ ├── terminal_solaris.go │ └── terminal_windows.go ├── metrics ├── FORK.md ├── LICENSE ├── README.md ├── counter.go ├── counter_test.go ├── debug.go ├── debug_test.go ├── disk.go ├── disk_linux.go ├── disk_nop.go ├── ewma.go ├── ewma_test.go ├── exp │ └── exp.go ├── gauge.go ├── gauge_float64.go ├── gauge_float64_test.go ├── gauge_test.go ├── graphite.go ├── graphite_test.go ├── healthcheck.go ├── histogram.go ├── histogram_test.go ├── influxdb │ ├── LICENSE │ ├── README.md │ └── influxdb.go ├── init_test.go ├── json.go ├── json_test.go ├── librato │ ├── client.go │ └── librato.go ├── log.go ├── memory.md ├── meter.go ├── meter_test.go ├── metrics.go ├── metrics_test.go ├── opentsdb.go ├── opentsdb_test.go ├── registry.go ├── registry_test.go ├── resetting_timer.go ├── resetting_timer_test.go ├── runtime.go ├── runtime_cgo.go ├── runtime_gccpufraction.go ├── runtime_no_cgo.go ├── runtime_no_gccpufraction.go ├── runtime_test.go ├── sample.go ├── sample_test.go ├── syslog.go ├── timer.go ├── timer_test.go ├── validate.sh ├── writer.go └── writer_test.go ├── params ├── bootnodes.go ├── config.go ├── config_test.go ├── dao.go ├── denomination.go ├── gas_table.go ├── network_params.go ├── protocol_params.go └── version.go ├── protobuf ├── lib.go ├── lib.pb.go ├── lib.proto └── lib_test.go ├── protocol ├── doc.go ├── protocol.go ├── protocol_test.go └── struct.go ├── rlp ├── decode.go ├── decode_tail_test.go ├── decode_test.go ├── doc.go ├── encode.go ├── encode_test.go ├── encoder_example_test.go ├── raw.go ├── raw_test.go └── typecache.go ├── service ├── doc.go ├── service.go └── service_test.go ├── simulation ├── cypherium.go ├── cypherium.toml ├── service.go ├── service.toml ├── simul.go ├── simul_test.go └── simulation ├── struct.go ├── trie ├── database.go ├── encoding.go ├── encoding_test.go ├── errors.go ├── hasher.go ├── iterator.go ├── iterator_test.go ├── node.go ├── node_test.go ├── proof.go ├── proof_test.go ├── secure_trie.go ├── secure_trie_test.go ├── sync.go ├── sync_test.go ├── trie.go └── trie_test.go └── txpool ├── error.go ├── events.go ├── evm.go ├── gaspool.go ├── genesis.go ├── state ├── database.go ├── dump.go ├── iterator.go ├── iterator_test.go ├── journal.go ├── main_test.go ├── managed_state.go ├── managed_state_test.go ├── state_object.go ├── state_test.go ├── statedb.go ├── statedb_test.go ├── sync.go └── sync_test.go ├── state_transition.go ├── tx_journal.go ├── tx_list.go ├── tx_pool.go ├── tx_pool_test.go ├── types ├── block.go ├── block_test.go ├── bloom9.go ├── bloom9_test.go ├── derive_sha.go ├── gen_header_json.go ├── gen_log_json.go ├── gen_receipt_json.go ├── key_block.go ├── log.go ├── log_test.go ├── receipt.go ├── transaction.go ├── transaction_signing.go ├── transaction_signing_test.go ├── transaction_test.go └── tx_block.go └── vm ├── analysis.go ├── analysis_test.go ├── common.go ├── contract.go ├── contracts.go ├── contracts_test.go ├── doc.go ├── errors.go ├── evm.go ├── gas.go ├── gas_table.go ├── gas_table_test.go ├── gen_structlog.go ├── instructions.go ├── instructions_test.go ├── int_pool_verifier.go ├── int_pool_verifier_empty.go ├── interface.go ├── interpreter.go ├── intpool.go ├── jump_table.go ├── logger.go ├── logger_test.go ├── memory.go ├── memory_table.go ├── noop.go ├── opcodes.go ├── runtime ├── doc.go ├── env.go ├── fuzz.go ├── runtime.go ├── runtime_example_test.go └── runtime_test.go ├── stack.go └── stack_table.go /CHANG: -------------------------------------------------------------------------------- 1 | 1. /Users/lwq/go/src/gopkg.in/dedis/crypto.v0/suites/list.go 中的type Suites map[string]abstract.Suite 和 2 | /Users/lwq/go/src/github.com/dedis/kyber/suites/suites.go 定义的不一样了 3 | 4 | // Suite is the sum of all suites mix-ins in Kyber. 5 | type Suite interface { 6 | kyber.Encoding 7 | kyber.Group 8 | kyber.HashFactory 9 | kyber.XOFFactory 10 | kyber.Random 11 | } 12 | 13 | var suites = map[string]Suite{} 14 | 15 | 16 | 17 | 2.cosi 18 | 19 | 20 | 3.abstract 21 | 22 | 4.suites 23 | 24 | 5.byzcoin -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | test_fmt: 4 | @echo Checking correct formatting of files 5 | @{ \ 6 | files=$$( go fmt ./... ); \ 7 | if [ -n "$$files" ]; then \ 8 | echo "Files not properly formatted: $$files"; \ 9 | exit 1; \ 10 | fi; \ 11 | if ! go vet ./...; then \ 12 | exit 1; \ 13 | fi \ 14 | } 15 | 16 | test_lint: 17 | @echo Checking linting of files 18 | @{ \ 19 | go get -u github.com/golang/lint/golint; \ 20 | lintfiles=$$( golint ./... ); \ 21 | if [ -n "$$lintfiles" ]; then \ 22 | echo "Lint errors:"; \ 23 | echo "$$lintfiles"; \ 24 | exit 1; \ 25 | fi \ 26 | } 27 | 28 | test_verbose: 29 | go test -v -race -short ./... 30 | 31 | # use test_verbose instead if you want to use this Makefile locally 32 | test_go: 33 | go test -race -short ./... 34 | 35 | test: test_fmt test_lint test_go -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go implementation of the Cypherium protocol/service/app 2 | 3 | ## Overview 4 | This repo is the official Go implementation of the Cypherium protocols, services and apps. Cypherium is a highly scalable & permission-less hybrid blockchain platform based on proof-of-work and Byzantine fault tolerance consensus. For more information, see: https://www.cypherium.io 5 | 6 | ## How to run the MVP version of Cypherium locally 7 | To use the code of this package you need to: 8 | 9 | - Install [Golang](https://golang.org/doc/install) 10 | - Optional: Set [`$GOPATH`](https://golang.org/doc/code.html#GOPATH) to point to your Go workspace directory 11 | - Add `$(go env GOPATH)/bin` to `$PATH` 12 | 13 | TODO 14 | 15 | 16 | ## Documentation 17 | 18 | You can find more documentation on the wiki: 19 | [Cypherium](https://github.com/cypherium/blockchain/wiki) 20 | 21 | 22 | ## License -------------------------------------------------------------------------------- /accounts/abi/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // Package abi implements the Ethereum ABI (Application Binary 18 | // Interface). 19 | // 20 | // The Ethereum ABI is strongly typed, known at compile time 21 | // and static. This ABI will handle basic type casting; unsigned 22 | // to signed and visa versa. It does not handle slice casting such 23 | // as unsigned slice to signed slice. Bit size type casting is also 24 | // handled. ints with a bit size of 32 will be properly cast to int256, 25 | // etc. 26 | package abi 27 | -------------------------------------------------------------------------------- /accounts/abi/numbers_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package abi 18 | 19 | import ( 20 | "bytes" 21 | "math/big" 22 | "reflect" 23 | "testing" 24 | ) 25 | 26 | func TestNumberTypes(t *testing.T) { 27 | ubytes := make([]byte, 32) 28 | ubytes[31] = 1 29 | 30 | unsigned := U256(big.NewInt(1)) 31 | if !bytes.Equal(unsigned, ubytes) { 32 | t.Errorf("expected %x got %x", ubytes, unsigned) 33 | } 34 | } 35 | 36 | func TestSigned(t *testing.T) { 37 | if isSigned(reflect.ValueOf(uint(10))) { 38 | t.Error("signed") 39 | } 40 | 41 | if !isSigned(reflect.ValueOf(int(10))) { 42 | t.Error("not signed") 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /accounts/keystore/keystore_plain.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package keystore 18 | 19 | import ( 20 | "encoding/json" 21 | "fmt" 22 | "os" 23 | "path/filepath" 24 | 25 | "github.com/cypherium_private/mvp/common" 26 | ) 27 | 28 | type keyStorePlain struct { 29 | keysDirPath string 30 | } 31 | 32 | func (ks keyStorePlain) GetKey(addr common.Address, filename, auth string) (*Key, error) { 33 | fd, err := os.Open(filename) 34 | if err != nil { 35 | return nil, err 36 | } 37 | defer fd.Close() 38 | key := new(Key) 39 | if err := json.NewDecoder(fd).Decode(key); err != nil { 40 | return nil, err 41 | } 42 | if key.Address != addr { 43 | return nil, fmt.Errorf("key content mismatch: have address %x, want %x", key.Address, addr) 44 | } 45 | return key, nil 46 | } 47 | 48 | func (ks keyStorePlain) StoreKey(filename string, key *Key, auth string) error { 49 | content, err := json.Marshal(key) 50 | if err != nil { 51 | return err 52 | } 53 | return writeKeyFile(filename, content) 54 | } 55 | 56 | func (ks keyStorePlain) JoinPath(filename string) string { 57 | if filepath.IsAbs(filename) { 58 | return filename 59 | } else { 60 | return filepath.Join(ks.keysDirPath, filename) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /accounts/keystore/testdata/dupes/1: -------------------------------------------------------------------------------- 1 | {"address":"f466859ead1932d743d622cb74fc058882e8648a","crypto":{"cipher":"aes-128-ctr","ciphertext":"cb664472deacb41a2e995fa7f96fe29ce744471deb8d146a0e43c7898c9ddd4d","cipherparams":{"iv":"dfd9ee70812add5f4b8f89d0811c9158"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"0d6769bf016d45c479213990d6a08d938469c4adad8a02ce507b4a4e7b7739f1"},"mac":"bac9af994b15a45dd39669fc66f9aa8a3b9dd8c22cb16e4d8d7ea089d0f1a1a9"},"id":"472e8b3d-afb6-45b5-8111-72c89895099a","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/dupes/2: -------------------------------------------------------------------------------- 1 | {"address":"f466859ead1932d743d622cb74fc058882e8648a","crypto":{"cipher":"aes-128-ctr","ciphertext":"cb664472deacb41a2e995fa7f96fe29ce744471deb8d146a0e43c7898c9ddd4d","cipherparams":{"iv":"dfd9ee70812add5f4b8f89d0811c9158"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"0d6769bf016d45c479213990d6a08d938469c4adad8a02ce507b4a4e7b7739f1"},"mac":"bac9af994b15a45dd39669fc66f9aa8a3b9dd8c22cb16e4d8d7ea089d0f1a1a9"},"id":"472e8b3d-afb6-45b5-8111-72c89895099a","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/dupes/foo: -------------------------------------------------------------------------------- 1 | {"address":"7ef5a6135f1fd6a02593eedc869c6d41d934aef8","crypto":{"cipher":"aes-128-ctr","ciphertext":"1d0839166e7a15b9c1333fc865d69858b22df26815ccf601b28219b6192974e1","cipherparams":{"iv":"8df6caa7ff1b00c4e871f002cb7921ed"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"e5e6ef3f4ea695f496b643ebd3f75c0aa58ef4070e90c80c5d3fb0241bf1595c"},"mac":"6d16dfde774845e4585357f24bce530528bc69f4f84e1e22880d34fa45c273e5"},"id":"950077c7-71e3-4c44-a4a1-143919141ed4","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/.hiddenfile: -------------------------------------------------------------------------------- 1 | {"address":"f466859ead1932d743d622cb74fc058882e8648a","crypto":{"cipher":"aes-128-ctr","ciphertext":"cb664472deacb41a2e995fa7f96fe29ce744471deb8d146a0e43c7898c9ddd4d","cipherparams":{"iv":"dfd9ee70812add5f4b8f89d0811c9158"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"0d6769bf016d45c479213990d6a08d938469c4adad8a02ce507b4a4e7b7739f1"},"mac":"bac9af994b15a45dd39669fc66f9aa8a3b9dd8c22cb16e4d8d7ea089d0f1a1a9"},"id":"472e8b3d-afb6-45b5-8111-72c89895099a","version":3} 2 | -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/README: -------------------------------------------------------------------------------- 1 | This directory contains accounts for testing. 2 | The passphrase that unlocks them is "foobar". 3 | 4 | The "good" key files which are supposed to be loadable are: 5 | 6 | - File: UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8 7 | Address: 0x7ef5a6135f1fd6a02593eedc869c6d41d934aef8 8 | - File: aaa 9 | Address: 0xf466859ead1932d743d622cb74fc058882e8648a 10 | - File: zzz 11 | Address: 0x289d485d9771714cce91d3393d764e1311907acc 12 | 13 | The other files (including this README) are broken in various ways 14 | and should not be picked up by package accounts: 15 | 16 | - File: no-address (missing address field, otherwise same as "aaa") 17 | - File: garbage (file with random data) 18 | - File: empty (file with no content) 19 | - File: swapfile~ (should be skipped) 20 | - File: .hiddenfile (should be skipped) 21 | - File: foo/... (should be skipped because it is a directory) 22 | -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8: -------------------------------------------------------------------------------- 1 | {"address":"7ef5a6135f1fd6a02593eedc869c6d41d934aef8","crypto":{"cipher":"aes-128-ctr","ciphertext":"1d0839166e7a15b9c1333fc865d69858b22df26815ccf601b28219b6192974e1","cipherparams":{"iv":"8df6caa7ff1b00c4e871f002cb7921ed"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"e5e6ef3f4ea695f496b643ebd3f75c0aa58ef4070e90c80c5d3fb0241bf1595c"},"mac":"6d16dfde774845e4585357f24bce530528bc69f4f84e1e22880d34fa45c273e5"},"id":"950077c7-71e3-4c44-a4a1-143919141ed4","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/aaa: -------------------------------------------------------------------------------- 1 | {"address":"f466859ead1932d743d622cb74fc058882e8648a","crypto":{"cipher":"aes-128-ctr","ciphertext":"cb664472deacb41a2e995fa7f96fe29ce744471deb8d146a0e43c7898c9ddd4d","cipherparams":{"iv":"dfd9ee70812add5f4b8f89d0811c9158"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"0d6769bf016d45c479213990d6a08d938469c4adad8a02ce507b4a4e7b7739f1"},"mac":"bac9af994b15a45dd39669fc66f9aa8a3b9dd8c22cb16e4d8d7ea089d0f1a1a9"},"id":"472e8b3d-afb6-45b5-8111-72c89895099a","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/accounts/keystore/testdata/keystore/empty -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/foo/fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e: -------------------------------------------------------------------------------- 1 | {"address":"fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e","crypto":{"cipher":"aes-128-ctr","ciphertext":"8124d5134aa4a927c79fd852989e4b5419397566f04b0936a1eb1d168c7c68a5","cipherparams":{"iv":"e2febe17176414dd2cda28287947eb2f"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":4096,"p":6,"r":8,"salt":"44b415ede89f3bdd6830390a21b78965f571b347a589d1d943029f016c5e8bd5"},"mac":"5e149ff25bfd9dd45746a84bb2bcd2f015f2cbca2b6d25c5de8c29617f71fe5b"},"id":"d6ac5452-2b2c-4d3c-ad80-4bf0327d971c","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/garbage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/accounts/keystore/testdata/keystore/garbage -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/no-address: -------------------------------------------------------------------------------- 1 | {"crypto":{"cipher":"aes-128-ctr","ciphertext":"cb664472deacb41a2e995fa7f96fe29ce744471deb8d146a0e43c7898c9ddd4d","cipherparams":{"iv":"dfd9ee70812add5f4b8f89d0811c9158"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"0d6769bf016d45c479213990d6a08d938469c4adad8a02ce507b4a4e7b7739f1"},"mac":"bac9af994b15a45dd39669fc66f9aa8a3b9dd8c22cb16e4d8d7ea089d0f1a1a9"},"id":"472e8b3d-afb6-45b5-8111-72c89895099a","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/zero: -------------------------------------------------------------------------------- 1 | {"address":"0000000000000000000000000000000000000000","crypto":{"cipher":"aes-128-ctr","ciphertext":"cb664472deacb41a2e995fa7f96fe29ce744471deb8d146a0e43c7898c9ddd4d","cipherparams":{"iv":"dfd9ee70812add5f4b8f89d0811c9158"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"0d6769bf016d45c479213990d6a08d938469c4adad8a02ce507b4a4e7b7739f1"},"mac":"bac9af994b15a45dd39669fc66f9aa8a3b9dd8c22cb16e4d8d7ea089d0f1a1a9"},"id":"472e8b3d-afb6-45b5-8111-72c89895099a","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/keystore/zzz: -------------------------------------------------------------------------------- 1 | {"address":"289d485d9771714cce91d3393d764e1311907acc","crypto":{"cipher":"aes-128-ctr","ciphertext":"faf32ca89d286b107f5e6d842802e05263c49b78d46eac74e6109e9a963378ab","cipherparams":{"iv":"558833eec4a665a8c55608d7d503407d"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"d571fff447ffb24314f9513f5160246f09997b857ac71348b73e785aab40dc04"},"mac":"21edb85ff7d0dab1767b9bf498f2c3cb7be7609490756bd32300bb213b59effe"},"id":"3279afcf-55ba-43ff-8997-02dcc46a6525","version":3} -------------------------------------------------------------------------------- /accounts/keystore/testdata/v1/cb61d5a9c4896fb9658090b597ef0e7be6f7b67e/cb61d5a9c4896fb9658090b597ef0e7be6f7b67e: -------------------------------------------------------------------------------- 1 | {"address":"cb61d5a9c4896fb9658090b597ef0e7be6f7b67e","Crypto":{"cipher":"aes-128-cbc","ciphertext":"6143d3192db8b66eabd693d9c4e414dcfaee52abda451af79ccf474dafb35f1bfc7ea013aa9d2ee35969a1a2e8d752d0","cipherparams":{"iv":"35337770fc2117994ecdcad026bccff4"},"kdf":"scrypt","kdfparams":{"n":262144,"r":8,"p":1,"dklen":32,"salt":"9afcddebca541253a2f4053391c673ff9fe23097cd8555d149d929e4ccf1257f"},"mac":"3f3d5af884b17a100b0b3232c0636c230a54dc2ac8d986227219b0dd89197644","version":"1"},"id":"e25f7c1f-d318-4f29-b62c-687190d4d299","version":"1"} -------------------------------------------------------------------------------- /accounts/keystore/testdata/v1_test_vector.json: -------------------------------------------------------------------------------- 1 | { 2 | "test1": { 3 | "json": { 4 | "Crypto": { 5 | "cipher": "aes-128-cbc", 6 | "cipherparams": { 7 | "iv": "35337770fc2117994ecdcad026bccff4" 8 | }, 9 | "ciphertext": "6143d3192db8b66eabd693d9c4e414dcfaee52abda451af79ccf474dafb35f1bfc7ea013aa9d2ee35969a1a2e8d752d0", 10 | "kdf": "scrypt", 11 | "kdfparams": { 12 | "dklen": 32, 13 | "n": 262144, 14 | "p": 1, 15 | "r": 8, 16 | "salt": "9afcddebca541253a2f4053391c673ff9fe23097cd8555d149d929e4ccf1257f" 17 | }, 18 | "mac": "3f3d5af884b17a100b0b3232c0636c230a54dc2ac8d986227219b0dd89197644", 19 | "version": "1" 20 | }, 21 | "address": "cb61d5a9c4896fb9658090b597ef0e7be6f7b67e", 22 | "id": "e25f7c1f-d318-4f29-b62c-687190d4d299", 23 | "version": "1" 24 | }, 25 | "password": "g", 26 | "priv": "d1b1178d3529626a1a93e073f65028370d14c7eb0936eb42abef05db6f37ad7d" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /accounts/keystore/testdata/very-light-scrypt.json: -------------------------------------------------------------------------------- 1 | {"address":"45dea0fb0bba44f4fcf290bba71fd57d7117cbb8","crypto":{"cipher":"aes-128-ctr","ciphertext":"b87781948a1befd247bff51ef4063f716cf6c2d3481163e9a8f42e1f9bb74145","cipherparams":{"iv":"dc4926b48a105133d2f16b96833abf1e"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":2,"p":1,"r":8,"salt":"004244bbdc51cadda545b1cfa43cff9ed2ae88e08c61f1479dbb45410722f8f0"},"mac":"39990c1684557447940d4c69e06b1b82b2aceacb43f284df65c956daf3046b85"},"id":"ce541d8d-c79b-40f8-9f8c-20f59616faba","version":3} 2 | -------------------------------------------------------------------------------- /accounts/keystore/watch_fallback.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build ios linux,arm64 windows !darwin,!freebsd,!linux,!netbsd,!solaris 18 | 19 | // This is the fallback implementation of directory watching. 20 | // It is used on unsupported platforms. 21 | 22 | package keystore 23 | 24 | type watcher struct{ running bool } 25 | 26 | func newWatcher(*accountCache) *watcher { return new(watcher) } 27 | func (*watcher) start() {} 28 | func (*watcher) close() {} 29 | -------------------------------------------------------------------------------- /accounts/usbwallet/internal/trezor/trezor.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // This file contains the implementation for interacting with the Trezor hardware 18 | // wallets. The wire protocol spec can be found on the SatoshiLabs website: 19 | // https://doc.satoshilabs.com/trezor-tech/api-protobuf.html 20 | 21 | //go:generate protoc --go_out=import_path=trezor:. types.proto messages.proto 22 | 23 | // Package trezor contains the wire protocol wrapper in Go. 24 | package trezor 25 | 26 | import ( 27 | "reflect" 28 | 29 | "github.com/golang/protobuf/proto" 30 | ) 31 | 32 | // Type returns the protocol buffer type number of a specific message. If the 33 | // message is nil, this method panics! 34 | func Type(msg proto.Message) uint16 { 35 | return uint16(MessageType_value["MessageType_"+reflect.TypeOf(msg).Elem().Name()]) 36 | } 37 | 38 | // Name returns the friendly message type name of a specific protocol buffer 39 | // type numbers. 40 | func Name(kind uint16) string { 41 | name := MessageType_name[int32(kind)] 42 | if len(name) < 12 { 43 | return name 44 | } 45 | return name[12:] 46 | } 47 | -------------------------------------------------------------------------------- /api_test.go: -------------------------------------------------------------------------------- 1 | package template_test 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/require" 7 | 8 | // We need to include the service so it is started. 9 | "github.com/cypherium_private/mvp" 10 | _ "github.com/cypherium_private/mvp/service" 11 | "github.com/dedis/kyber/suites" 12 | "github.com/dedis/onet" 13 | "github.com/dedis/onet/log" 14 | ) 15 | 16 | var tSuite = suites.MustFind("Ed25519") 17 | 18 | func TestMain(m *testing.M) { 19 | log.MainTest(m) 20 | } 21 | 22 | func TestClient_Clock(t *testing.T) { 23 | nbr := 5 24 | local := onet.NewTCPTest(tSuite) 25 | // generate 5 hosts, they don't connect, they process messages, and they 26 | // don't register the tree or entitylist 27 | _, roster, _ := local.GenTree(nbr, true) 28 | defer local.CloseAll() 29 | 30 | c := template.NewClient() 31 | cl1, err := c.Clock(roster) 32 | require.Nil(t, err) 33 | require.Equal(t, nbr, cl1.Children) 34 | cl2, err := c.Clock(roster) 35 | require.Nil(t, err) 36 | require.Equal(t, nbr, cl2.Children) 37 | } 38 | 39 | func TestClient_Count(t *testing.T) { 40 | nbr := 5 41 | local := onet.NewTCPTest(tSuite) 42 | // generate 5 hosts, they don't connect, they process messages, and they 43 | // don't register the tree or entitylist 44 | _, roster, _ := local.GenTree(nbr, true) 45 | defer local.CloseAll() 46 | 47 | c := template.NewClient() 48 | // Verify it's all 0s before 49 | for _, s := range roster.List { 50 | count, err := c.Count(s) 51 | require.Nil(t, err) 52 | require.Equal(t, 0, count) 53 | } 54 | 55 | // Make some clock-requests 56 | for range roster.List { 57 | _, err := c.Clock(roster) 58 | require.Nil(t, err) 59 | } 60 | 61 | // Verify we have the correct total of requests 62 | total := 0 63 | for _, s := range roster.List { 64 | count, err := c.Count(s) 65 | require.Nil(t, err) 66 | total += count 67 | } 68 | require.Equal(t, nbr, total) 69 | } 70 | -------------------------------------------------------------------------------- /app/mock_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | //"github.com/syndtr/goleveldb/leveldb" 6 | "golang.org/x/crypto/ed25519" 7 | "testing" 8 | ) 9 | 10 | var num int = 10 11 | 12 | func TestStxGen(t *testing.T) { 13 | if err := GenStxs(num); err != nil { 14 | t.Error("Failed") 15 | } 16 | } 17 | 18 | func TestStxVerify(t *testing.T) { 19 | stxs := GetStxs(num) 20 | for i := 0; i < num; i++ { 21 | fmt.Printf("%+v\n", stxs[i]) 22 | } 23 | for i := 0; i < num; i++ { 24 | sig := stxs[i].GetSenderSig() 25 | msg := []byte(stxs[i].GetTx().String()) 26 | pk := stxs[i].GetTx().GetSenderKey() 27 | ok := ed25519.Verify(pk, msg, sig) 28 | if ok == false { 29 | t.Errorf("STx %d not valid\n", i) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /app/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | DBG_TEST=1 4 | # Debug-level for app 5 | DBG_APP=2 6 | 7 | . $(go env GOPATH)/src/github.com/dedis/onet/app/libtest.sh 8 | 9 | main(){ 10 | startTest 11 | buildConode 12 | test Count 13 | test Time 14 | stopTest 15 | } 16 | 17 | testCount(){ 18 | runCoBG 1 2 19 | testFail runTmpl counter 20 | testOK runTmpl counter public.toml 21 | testGrep ": 0" runTmpl counter public.toml 22 | runTmpl time public.toml 23 | testGrep ": 1" runTmpl counter public.toml 24 | } 25 | 26 | testTime(){ 27 | runCoBG 1 2 28 | testFail runTmpl time 29 | testOK runTmpl time public.toml 30 | testGrep Time runTmpl time public.toml 31 | } 32 | 33 | testBuild(){ 34 | testOK dbgRun runTmpl --help 35 | } 36 | 37 | runTmpl(){ 38 | dbgRun ./$APP -d $DBG_APP $@ 39 | } 40 | 41 | main 42 | -------------------------------------------------------------------------------- /blockchain/blkparser/block.go: -------------------------------------------------------------------------------- 1 | // Basically adapation from the file at https://github.com/tsileo/blkparser 2 | package blkparser 3 | 4 | import ( 5 | "bytes" 6 | "encoding/binary" 7 | ) 8 | 9 | type Block struct { 10 | Raw []byte `json:"-"` 11 | Hash string `json:"hash"` 12 | Height uint `json:"height"` 13 | Txs []*Tx `json:"tx,omitempty"` 14 | Version uint32 `json:"ver"` 15 | MerkleRoot string `json:"mrkl_root"` 16 | BlockTime uint32 `json:"time"` 17 | Bits uint32 `json:"bits"` 18 | Nonce uint32 `json:"nonce"` 19 | Size uint32 `json:"size"` 20 | TxCnt uint32 `json:"n_tx"` 21 | TotalBTC uint64 `json:"total_out"` 22 | BlockReward float64 `json:"-"` 23 | Parent string `json:"prev_block"` 24 | Next string `json:"next_block"` 25 | } 26 | 27 | func NewBlock(rawblock []byte) (block *Block, err error) { 28 | block = new(Block) 29 | block.Raw = rawblock 30 | 31 | block.Hash = GetShaString(rawblock[0:80]) 32 | block.Version = binary.LittleEndian.Uint32(rawblock[0:4]) 33 | if !bytes.Equal(rawblock[4:36], []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) { 34 | block.Parent = HashString(rawblock[4:36]) 35 | } 36 | block.MerkleRoot = HashString(rawblock[36:68]) 37 | block.BlockTime = binary.LittleEndian.Uint32(rawblock[68:72]) 38 | block.Bits = binary.LittleEndian.Uint32(rawblock[72:76]) 39 | block.Nonce = binary.LittleEndian.Uint32(rawblock[76:80]) 40 | block.Size = uint32(len(rawblock)) 41 | 42 | txs, _ := ParseTxs(rawblock[80:]) 43 | 44 | block.Txs = txs 45 | 46 | return 47 | } 48 | -------------------------------------------------------------------------------- /blockchain/blkparser/utils.go: -------------------------------------------------------------------------------- 1 | // Package blkparser basically is an adaptation from a file at https://github.com/tsileo/blkparser 2 | package blkparser 3 | 4 | import ( 5 | "crypto/sha256" 6 | "fmt" 7 | 8 | "github.com/dedis/onet/log" 9 | ) 10 | 11 | // Get the Tx count, decode the variable length integer 12 | // https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer 13 | func DecodeVariableLengthInteger(raw []byte) (cnt int, cnt_size int) { 14 | if raw[0] < 0xfd { 15 | return int(raw[0]), 1 16 | } 17 | cnt_size = 1 + (2 << (2 - (0xff - raw[0]))) 18 | if len(raw) < 1+cnt_size { 19 | return 20 | } 21 | 22 | res := uint64(0) 23 | for i := 1; i < cnt_size; i++ { 24 | res |= (uint64(raw[i]) << uint64(8*(i-1))) 25 | } 26 | 27 | cnt = int(res) 28 | return 29 | } 30 | 31 | func GetShaString(data []byte) (res string) { 32 | sha := sha256.New() 33 | if _, err := sha.Write(data[:]); err != nil { 34 | log.Error("Failed to hash data", err) 35 | } 36 | tmp := sha.Sum(nil) 37 | sha.Reset() 38 | if _, err := sha.Write(tmp); err != nil { 39 | log.Error("Failed to hash data", err) 40 | } 41 | hash := sha.Sum(nil) 42 | res = HashString(hash) 43 | return 44 | } 45 | 46 | func HashString(data []byte) (res string) { 47 | for i := 0; i < 32; i++ { 48 | res += fmt.Sprintf("%02x", data[31-i]) 49 | } 50 | return 51 | } 52 | -------------------------------------------------------------------------------- /blockchain/common.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | const ( 4 | AddrLen = 20 5 | PubKeyLen = 32 6 | PrvKeyLen = 64 7 | HashLen = 32 8 | SigLen = 64 9 | AggrLen = 64 10 | ) 11 | 12 | type ( 13 | Address [AddrLen]byte 14 | PubKey [PubKeyLen]byte 15 | PrvKey [PrvKeyLen]byte 16 | Hash [HashLen]byte 17 | Signature [SigLen]byte 18 | AggrAddr [AggrLen]byte 19 | ) 20 | -------------------------------------------------------------------------------- /blockchain/keyblock.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "golang.org/x/crypto/sha3" 5 | //"log" 6 | "net" 7 | ) 8 | 9 | /* 10 | type KeyBlock struct { 11 | Block 12 | } 13 | */ 14 | 15 | func (*KeyBlock) NewKeyBlock(transactions TxBlockData, header *KeyBlockHdr) (tr KeyBlock) { 16 | kb := new(KeyBlock) 17 | //kb.HeaderHash = kb.Hash(header) 18 | //kb.TransactionList = transactions 19 | //kb.BlockSize = 0 20 | kb.Kbh = header 21 | return *kb 22 | } 23 | 24 | func (trb *KeyBlock) Hash(h *KeyBlockHdr) (res []byte) { 25 | HStr := h.String() 26 | HSha := sha3.Sum256([]byte(HStr)) 27 | return HSha[:] 28 | } 29 | 30 | func (t *KeyBlock) NewHeader(transactions TxBlockData, parent string, IP net.IP, key string) (hd KeyBlockHdr) { 31 | hdr := new(KeyBlockHdr) 32 | //hdr.LeaderId = IP 33 | hdr.Version = 0 34 | //hdr.PublicKey = key 35 | hdr.PKblkHash = []byte(parent) 36 | //hdr.MerkleRoot = t.Calculate_root(transactions) 37 | return *hdr 38 | } 39 | 40 | /* 41 | func (trb *KeyBlock) Print() { 42 | log.Println("Header:") 43 | log.Printf("Leader %v", trb.LeaderId) 44 | //log.Printf("Pkey %v", trb.PublicKey) 45 | log.Printf("ParentKey %v", trb.ParentKey) 46 | log.Printf("Merkle %v", trb.MerkleRoot) 47 | //log.Println("Rest:") 48 | log.Printf("Hash %v", trb.HeaderHash) 49 | return 50 | } 51 | */ 52 | -------------------------------------------------------------------------------- /blockchain/proof_test.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "crypto/sha256" 5 | "testing" 6 | ) 7 | 8 | func TestPath(t *testing.T) { 9 | 10 | newHash := sha256.New 11 | hash := newHash() 12 | n := 13 13 | 14 | leaves := make([]HashID, n) 15 | for i := range leaves { 16 | leaves[i] = make([]byte, hash.Size()) 17 | for j := range leaves[i] { 18 | leaves[i][j] = byte(i) 19 | } 20 | // println("leaf", i, ":", hex.EncodeToString(leaves[i])) 21 | // fmt.Println("leaf", i, ":", leaves[i]) 22 | } 23 | 24 | root, proofs := ProofTree(newHash, leaves) 25 | for i := range proofs { 26 | if proofs[i].Check(newHash, root, leaves[i]) == false { 27 | t.Error("check failed at leaf", i) 28 | } 29 | } 30 | } 31 | 32 | func TestPathLong(t *testing.T) { 33 | if testing.Short() { 34 | t.Skip("Test takes too long - skipping test in short mode.") 35 | } 36 | 37 | newHash := sha256.New 38 | hash := newHash() 39 | n := 100 // takes 6 seconds 40 | for k := 0; k < n; k++ { 41 | leaves := make([]HashID, k) 42 | for i := range leaves { 43 | leaves[i] = make([]byte, hash.Size()) 44 | for j := range leaves[i] { 45 | leaves[i][j] = byte(i) 46 | } 47 | } 48 | 49 | root, proofs := ProofTree(newHash, leaves) 50 | for i := range proofs { 51 | if proofs[i].Check(newHash, root, leaves[i]) == false { 52 | t.Error("check failed at leaf", i) 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /common/big.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import "math/big" 20 | 21 | // Common big integers often used 22 | var ( 23 | Big1 = big.NewInt(1) 24 | Big2 = big.NewInt(2) 25 | Big3 = big.NewInt(3) 26 | Big0 = big.NewInt(0) 27 | Big32 = big.NewInt(32) 28 | Big256 = big.NewInt(256) 29 | Big257 = big.NewInt(257) 30 | ) 31 | -------------------------------------------------------------------------------- /common/bitutil/compress_fuzz.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build gofuzz 18 | 19 | package bitutil 20 | 21 | import "bytes" 22 | 23 | // Fuzz implements a go-fuzz fuzzer method to test various encoding method 24 | // invocations. 25 | func Fuzz(data []byte) int { 26 | if len(data) == 0 { 27 | return -1 28 | } 29 | if data[0]%2 == 0 { 30 | return fuzzEncode(data[1:]) 31 | } 32 | return fuzzDecode(data[1:]) 33 | } 34 | 35 | // fuzzEncode implements a go-fuzz fuzzer method to test the bitset encoding and 36 | // decoding algorithm. 37 | func fuzzEncode(data []byte) int { 38 | proc, _ := bitsetDecodeBytes(bitsetEncodeBytes(data), len(data)) 39 | if !bytes.Equal(data, proc) { 40 | panic("content mismatch") 41 | } 42 | return 0 43 | } 44 | 45 | // fuzzDecode implements a go-fuzz fuzzer method to test the bit decoding and 46 | // reencoding algorithm. 47 | func fuzzDecode(data []byte) int { 48 | blob, err := bitsetDecodeBytes(data, 1024) 49 | if err != nil { 50 | return 0 51 | } 52 | if comp := bitsetEncodeBytes(blob); !bytes.Equal(comp, data) { 53 | panic("content mismatch") 54 | } 55 | return 0 56 | } 57 | -------------------------------------------------------------------------------- /common/debug.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | "runtime" 23 | "runtime/debug" 24 | "strings" 25 | ) 26 | 27 | // Report gives off a warning requesting the user to submit an issue to the github tracker. 28 | func Report(extra ...interface{}) { 29 | fmt.Fprintln(os.Stderr, "You've encountered a sought after, hard to reproduce bug. Please report this to the developers <3 https://github.com/cypherium_private/mvp/issues") 30 | fmt.Fprintln(os.Stderr, extra...) 31 | 32 | _, file, line, _ := runtime.Caller(1) 33 | fmt.Fprintf(os.Stderr, "%v:%v\n", file, line) 34 | 35 | debug.PrintStack() 36 | 37 | fmt.Fprintln(os.Stderr, "#### BUG! PLEASE REPORT ####") 38 | } 39 | 40 | // PrintDepricationWarning prinst the given string in a box using fmt.Println. 41 | func PrintDepricationWarning(str string) { 42 | line := strings.Repeat("#", len(str)+4) 43 | emptyLine := strings.Repeat(" ", len(str)) 44 | fmt.Printf(` 45 | %s 46 | # %s # 47 | # %s # 48 | # %s # 49 | %s 50 | 51 | `, line, emptyLine, str, emptyLine, line) 52 | } 53 | -------------------------------------------------------------------------------- /common/fdlimit/fdlimit_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package fdlimit 18 | 19 | import ( 20 | "fmt" 21 | "testing" 22 | ) 23 | 24 | // TestFileDescriptorLimits simply tests whether the file descriptor allowance 25 | // per this process can be retrieved. 26 | func TestFileDescriptorLimits(t *testing.T) { 27 | target := 4096 28 | hardlimit, err := Maximum() 29 | if err != nil { 30 | t.Fatal(err) 31 | } 32 | if hardlimit < target { 33 | t.Skip(fmt.Sprintf("system limit is less than desired test target: %d < %d", hardlimit, target)) 34 | } 35 | 36 | if limit, err := Current(); err != nil || limit <= 0 { 37 | t.Fatalf("failed to retrieve file descriptor limit (%d): %v", limit, err) 38 | } 39 | if err := Raise(uint64(target)); err != nil { 40 | t.Fatalf("failed to raise file allowance") 41 | } 42 | if limit, err := Current(); err != nil || limit < target { 43 | t.Fatalf("failed to retrieve raised descriptor limit (have %v, want %v): %v", limit, target, err) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /common/format.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import ( 20 | "fmt" 21 | "regexp" 22 | "strings" 23 | "time" 24 | ) 25 | 26 | // PrettyDuration is a pretty printed version of a time.Duration value that cuts 27 | // the unnecessary precision off from the formatted textual representation. 28 | type PrettyDuration time.Duration 29 | 30 | var prettyDurationRe = regexp.MustCompile(`\.[0-9]+`) 31 | 32 | // String implements the Stringer interface, allowing pretty printing of duration 33 | // values rounded to three decimals. 34 | func (d PrettyDuration) String() string { 35 | label := fmt.Sprintf("%v", time.Duration(d)) 36 | if match := prettyDurationRe.FindString(label); len(match) > 4 { 37 | label = strings.Replace(label, match, match[:4], 1) 38 | } 39 | return label 40 | } 41 | -------------------------------------------------------------------------------- /common/hexutil/json_example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package hexutil_test 18 | 19 | import ( 20 | "encoding/json" 21 | "fmt" 22 | 23 | "github.com/cypherium_private/mvp/common/hexutil" 24 | ) 25 | 26 | type MyType [5]byte 27 | 28 | func (v *MyType) UnmarshalText(input []byte) error { 29 | return hexutil.UnmarshalFixedText("MyType", input, v[:]) 30 | } 31 | 32 | func (v MyType) String() string { 33 | return hexutil.Bytes(v[:]).String() 34 | } 35 | 36 | func ExampleUnmarshalFixedText() { 37 | var v1, v2 MyType 38 | fmt.Println("v1 error:", json.Unmarshal([]byte(`"0x01"`), &v1)) 39 | fmt.Println("v2 error:", json.Unmarshal([]byte(`"0x0101010101"`), &v2)) 40 | fmt.Println("v2:", v2) 41 | // Output: 42 | // v1 error: hex string has length 2, want 10 for MyType 43 | // v2 error: 44 | // v2: 0x0101010101 45 | } 46 | -------------------------------------------------------------------------------- /common/main_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import ( 20 | "testing" 21 | 22 | checker "gopkg.in/check.v1" 23 | ) 24 | 25 | func Test(t *testing.T) { checker.TestingT(t) } 26 | -------------------------------------------------------------------------------- /common/mclock/mclock.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // package mclock is a wrapper for a monotonic clock source 18 | package mclock 19 | 20 | import ( 21 | "time" 22 | 23 | "github.com/aristanetworks/goarista/monotime" 24 | ) 25 | 26 | type AbsTime time.Duration // absolute monotonic time 27 | 28 | func Now() AbsTime { 29 | return AbsTime(monotime.Now()) 30 | } 31 | -------------------------------------------------------------------------------- /common/path.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | "path/filepath" 23 | "runtime" 24 | ) 25 | 26 | // MakeName creates a node name that follows the ethereum convention 27 | // for such names. It adds the operation system name and Go runtime version 28 | // the name. 29 | func MakeName(name, version string) string { 30 | return fmt.Sprintf("%s/v%s/%s/%s", name, version, runtime.GOOS, runtime.Version()) 31 | } 32 | 33 | func FileExist(filePath string) bool { 34 | _, err := os.Stat(filePath) 35 | if err != nil && os.IsNotExist(err) { 36 | return false 37 | } 38 | 39 | return true 40 | } 41 | 42 | func AbsolutePath(Datadir string, filename string) string { 43 | if filepath.IsAbs(filename) { 44 | return filename 45 | } 46 | return filepath.Join(Datadir, filename) 47 | } 48 | -------------------------------------------------------------------------------- /common/size.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import ( 20 | "fmt" 21 | ) 22 | 23 | // StorageSize is a wrapper around a float value that supports user friendly 24 | // formatting. 25 | type StorageSize float64 26 | 27 | // String implements the stringer interface. 28 | func (s StorageSize) String() string { 29 | if s > 1000000 { 30 | return fmt.Sprintf("%.2f mB", s/1000000) 31 | } else if s > 1000 { 32 | return fmt.Sprintf("%.2f kB", s/1000) 33 | } else { 34 | return fmt.Sprintf("%.2f B", s) 35 | } 36 | } 37 | 38 | // TerminalString implements log.TerminalStringer, formatting a string for console 39 | // output during logging. 40 | func (s StorageSize) TerminalString() string { 41 | if s > 1000000 { 42 | return fmt.Sprintf("%.2fmB", s/1000000) 43 | } else if s > 1000 { 44 | return fmt.Sprintf("%.2fkB", s/1000) 45 | } else { 46 | return fmt.Sprintf("%.2fB", s) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /common/size_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import ( 20 | "testing" 21 | ) 22 | 23 | func TestStorageSizeString(t *testing.T) { 24 | tests := []struct { 25 | size StorageSize 26 | str string 27 | }{ 28 | {2381273, "2.38 mB"}, 29 | {2192, "2.19 kB"}, 30 | {12, "12.00 B"}, 31 | } 32 | 33 | for _, test := range tests { 34 | if test.size.String() != test.str { 35 | t.Errorf("%f: got %q, want %q", float64(test.size), test.size.String(), test.str) 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /common/test_utils.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package common 18 | 19 | import ( 20 | "encoding/json" 21 | "fmt" 22 | "io/ioutil" 23 | ) 24 | 25 | // LoadJSON reads the given file and unmarshals its content. 26 | func LoadJSON(file string, val interface{}) error { 27 | content, err := ioutil.ReadFile(file) 28 | if err != nil { 29 | return err 30 | } 31 | if err := json.Unmarshal(content, val); err != nil { 32 | if syntaxerr, ok := err.(*json.SyntaxError); ok { 33 | line := findLine(content, syntaxerr.Offset) 34 | return fmt.Errorf("JSON syntax error at %v:%v: %v", file, line, err) 35 | } 36 | return fmt.Errorf("JSON unmarshal error in %v: %v", file, err) 37 | } 38 | return nil 39 | } 40 | 41 | // findLine returns the line number for the given offset into data. 42 | func findLine(data []byte, offset int64) (line int) { 43 | line = 1 44 | for i, r := range string(data) { 45 | if int64(i) >= offset { 46 | return 47 | } 48 | if r == '\n' { 49 | line++ 50 | } 51 | } 52 | return 53 | } 54 | -------------------------------------------------------------------------------- /conode/conode_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "os" 7 | 8 | "github.com/dedis/onet/log" 9 | ) 10 | 11 | func TestMain(m *testing.M) { 12 | log.MainTest(m) 13 | } 14 | 15 | func TestRun(t *testing.T) { 16 | os.Args = []string{os.Args[0], "--help"} 17 | main() 18 | } 19 | -------------------------------------------------------------------------------- /conode/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | DBG_TEST=1 4 | DBG_APP=2 5 | 6 | . $(go env GOPATH)/src/github.com/dedis/onet/app/libtest.sh 7 | 8 | main(){ 9 | startTest 10 | setupConode 11 | test Build 12 | stopTest 13 | } 14 | 15 | testBuild(){ 16 | cp co1/public.toml . 17 | testOK dbgRun runCo 1 --help 18 | } 19 | 20 | main 21 | -------------------------------------------------------------------------------- /cosi/cosi_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | ) 7 | 8 | func TestMainFunc(t *testing.T) { 9 | os.Args = []string{os.Args[0], "--help"} 10 | main() 11 | } 12 | -------------------------------------------------------------------------------- /cosi/crypto/README.md: -------------------------------------------------------------------------------- 1 | This is a copy of gopkg.in/dedis/crypto.v0/cosi in order to help us 2 | port Cothority to the new kyber without getting stuck. -------------------------------------------------------------------------------- /cosi/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "gopkg.in/urfave/cli.v1" 5 | 6 | // Empty imports to have the init-functions called which should 7 | // register the protocol 8 | 9 | _ "github.com/dedis/cothority/cosi/protocol" 10 | _ "github.com/dedis/cothority/cosi/service" 11 | "github.com/dedis/onet/app" 12 | ) 13 | 14 | func runServer(ctx *cli.Context) { 15 | // first check the options 16 | config := ctx.String("config") 17 | 18 | app.RunServer(config) 19 | } 20 | -------------------------------------------------------------------------------- /cosi/server_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/dedis/onet/log" 7 | ) 8 | 9 | func TestMain(m *testing.M) { 10 | log.MainTest(m) 11 | } 12 | -------------------------------------------------------------------------------- /cosi/service/api.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/dedis/cothority" 7 | "github.com/dedis/onet" 8 | "github.com/dedis/onet/log" 9 | ) 10 | 11 | // Client is a structure to communicate with the CoSi 12 | // service 13 | type Client struct { 14 | *onet.Client 15 | } 16 | 17 | // NewClient instantiates a new cosi.Client 18 | func NewClient() *Client { 19 | return &Client{Client: onet.NewClient(cothority.Suite, ServiceName)} 20 | } 21 | 22 | // SignatureRequest sends a CoSi sign request to the Cothority defined by the given 23 | // Roster 24 | func (c *Client) SignatureRequest(r *onet.Roster, msg []byte) (*SignatureResponse, error) { 25 | serviceReq := &SignatureRequest{ 26 | Roster: r, 27 | Message: msg, 28 | } 29 | if len(r.List) == 0 { 30 | return nil, errors.New("Got an empty roster-list") 31 | } 32 | dst := r.List[0] 33 | log.Lvl4("Sending message to", dst) 34 | reply := &SignatureResponse{} 35 | err := c.SendProtobuf(dst, serviceReq, reply) 36 | if err != nil { 37 | return nil, err 38 | } 39 | return reply, nil 40 | } 41 | -------------------------------------------------------------------------------- /cosi/service/cosi.proto: -------------------------------------------------------------------------------- 1 | import "../network.proto"; 2 | 3 | message SignatureRequest { 4 | required bytes message = 1; 5 | required Roster roster = 2; 6 | } 7 | 8 | message SignatureResponse { 9 | required bytes hash = 1; 10 | required bytes signature = 2; 11 | } 12 | -------------------------------------------------------------------------------- /cosi/simulation/cosi.toml: -------------------------------------------------------------------------------- 1 | Simulation = "CoSimul" 2 | Servers = 16 3 | Bf = 3 4 | Rounds = 10 5 | RunWait = "6000s" 6 | Suite = "Ed25519" 7 | 8 | Depth 9 | 1 10 | 2 11 | 3 12 | -------------------------------------------------------------------------------- /cosi/simulation/cosi_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/dedis/cothority" 8 | "github.com/dedis/cothority/cosi/crypto" 9 | "github.com/dedis/onet" 10 | "github.com/dedis/onet/log" 11 | ) 12 | 13 | var tSuite = cothority.Suite 14 | 15 | func TestMain(m *testing.M) { 16 | raiseLimit() 17 | log.MainTest(m) 18 | } 19 | 20 | func TestCoSimul(t *testing.T) { 21 | for v := 0; v < 3; v++ { 22 | for _, nbrHosts := range []int{1, 3, 13} { 23 | log.Lvl2("Running cosi with", nbrHosts, "hosts") 24 | local := onet.NewLocalTest(tSuite) 25 | 26 | hosts, _, tree := local.GenBigTree(nbrHosts, nbrHosts, 3, true) 27 | log.Lvl2(tree.Dump()) 28 | 29 | done := make(chan bool) 30 | // create the message we want to sign for this round 31 | msg := []byte("Hello World Cosi") 32 | 33 | // Register the function generating the protocol instance 34 | var root *CoSimul 35 | // function that will be called when protocol is finished by the root 36 | doneFunc := func(sig []byte) { 37 | suite := hosts[0].Suite() 38 | if err := crypto.VerifySignature(suite, root.Publics(), msg, sig); err != nil { 39 | t.Fatal("error verifying signature:", err) 40 | } else { 41 | log.Lvl1("Verification OK") 42 | } 43 | done <- true 44 | } 45 | 46 | // Start the protocol 47 | p, err := local.CreateProtocol(Name, tree) 48 | if err != nil { 49 | t.Fatal("Couldn't create new node:", err) 50 | } 51 | root = p.(*CoSimul) 52 | root.Message = msg 53 | root.VerifyResponse = VRType(v) 54 | root.RegisterSignatureHook(doneFunc) 55 | go root.Start() 56 | select { 57 | case <-done: 58 | case <-time.After(time.Second * 2): 59 | t.Fatal("Could not get signature verification done in time") 60 | } 61 | local.CloseAll() 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /cosi/simulation/cosi_verification.toml: -------------------------------------------------------------------------------- 1 | Servers = 8 2 | Simulation = "CoSimul" 3 | Rounds = 5 4 | Depth = 2 5 | BF = 4 6 | Suite = "Ed25519" 7 | 8 | Checking 9 | 0 10 | 1 11 | 2 12 | -------------------------------------------------------------------------------- /cosi/simulation/fd_test.go: -------------------------------------------------------------------------------- 1 | // +build !darwin,!linux 2 | 3 | package main 4 | 5 | func raiseLimit() {} 6 | -------------------------------------------------------------------------------- /cosi/simulation/fd_unix_test.go: -------------------------------------------------------------------------------- 1 | // +build darwin linux 2 | 3 | package main 4 | 5 | import ( 6 | "log" 7 | "syscall" 8 | ) 9 | 10 | func raiseLimit() { 11 | // Raising the FD limit like this might belong in a more central place, 12 | // but for the moment, this is the only test where it is biting us. 13 | // (and even then, only for Jeff's Mac: why?) 14 | var rLimit syscall.Rlimit 15 | err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) 16 | if err != nil { 17 | log.Fatal("Error Getting Rlimit ", err) 18 | } 19 | 20 | if rLimit.Cur < 2048 { 21 | rLimit.Cur = 2048 22 | err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) 23 | if err != nil { 24 | log.Fatal("Error Setting Rlimit ", err) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cosi/simulation/simul.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/dedis/onet/simul" 5 | ) 6 | 7 | func main() { 8 | simul.Start() 9 | } 10 | -------------------------------------------------------------------------------- /cosi/simulation/simul_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | ) 7 | 8 | func TestSimulation(t *testing.T) { 9 | os.Args = []string{os.Args[0], "cosi.toml"} 10 | main() 11 | os.Args = []string{os.Args[0], "cosi_verification.toml"} 12 | main() 13 | } 14 | -------------------------------------------------------------------------------- /crypto/bn256/bn256_fast.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build amd64 arm64 18 | 19 | // Package bn256 implements the Optimal Ate pairing over a 256-bit Barreto-Naehrig curve. 20 | package bn256 21 | 22 | import "github.com/cypherium_private/mvp/crypto/bn256/cloudflare" 23 | 24 | // G1 is an abstract cyclic group. The zero value is suitable for use as the 25 | // output of an operation, but cannot be used as an input. 26 | type G1 = bn256.G1 27 | 28 | // G2 is an abstract cyclic group. The zero value is suitable for use as the 29 | // output of an operation, but cannot be used as an input. 30 | type G2 = bn256.G2 31 | 32 | // PairingCheck calculates the Optimal Ate pairing for a set of points. 33 | func PairingCheck(a []*G1, b []*G2) bool { 34 | return bn256.PairingCheck(a, b) 35 | } 36 | -------------------------------------------------------------------------------- /crypto/bn256/bn256_slow.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build !amd64,!arm64 18 | 19 | // Package bn256 implements the Optimal Ate pairing over a 256-bit Barreto-Naehrig curve. 20 | package bn256 21 | 22 | import "github.com/cypherium_private/mvp/crypto/bn256/google" 23 | 24 | // G1 is an abstract cyclic group. The zero value is suitable for use as the 25 | // output of an operation, but cannot be used as an input. 26 | type G1 = bn256.G1 27 | 28 | // G2 is an abstract cyclic group. The zero value is suitable for use as the 29 | // output of an operation, but cannot be used as an input. 30 | type G2 = bn256.G2 31 | 32 | // PairingCheck calculates the Optimal Ate pairing for a set of points. 33 | func PairingCheck(a []*G1, b []*G2) bool { 34 | return bn256.PairingCheck(a, b) 35 | } 36 | -------------------------------------------------------------------------------- /crypto/bn256/cloudflare/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package bn256 6 | 7 | import ( 8 | "crypto/rand" 9 | "testing" 10 | 11 | "github.com/stretchr/testify/require" 12 | ) 13 | 14 | func TestExamplePair(t *testing.T) { 15 | // This implements the tripartite Diffie-Hellman algorithm from "A One 16 | // Round Protocol for Tripartite Diffie-Hellman", A. Joux. 17 | // http://www.springerlink.com/content/cddc57yyva0hburb/fulltext.pdf 18 | 19 | // Each of three parties, a, b and c, generate a private value. 20 | a, _ := rand.Int(rand.Reader, Order) 21 | b, _ := rand.Int(rand.Reader, Order) 22 | c, _ := rand.Int(rand.Reader, Order) 23 | 24 | // Then each party calculates g₁ and g₂ times their private value. 25 | pa := new(G1).ScalarBaseMult(a) 26 | qa := new(G2).ScalarBaseMult(a) 27 | 28 | pb := new(G1).ScalarBaseMult(b) 29 | qb := new(G2).ScalarBaseMult(b) 30 | 31 | pc := new(G1).ScalarBaseMult(c) 32 | qc := new(G2).ScalarBaseMult(c) 33 | 34 | // Now each party exchanges its public values with the other two and 35 | // all parties can calculate the shared key. 36 | k1 := Pair(pb, qc) 37 | k1.ScalarMult(k1, a) 38 | 39 | k2 := Pair(pc, qa) 40 | k2.ScalarMult(k2, b) 41 | 42 | k3 := Pair(pa, qb) 43 | k3.ScalarMult(k3, c) 44 | 45 | // k1, k2 and k3 will all be equal. 46 | 47 | require.Equal(t, k1, k2) 48 | require.Equal(t, k1, k3) 49 | 50 | require.Equal(t, len(np), 4) //Avoid gometalinter varcheck err on np 51 | } 52 | -------------------------------------------------------------------------------- /crypto/bn256/cloudflare/gfp.go: -------------------------------------------------------------------------------- 1 | package bn256 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | type gfP [4]uint64 9 | 10 | func newGFp(x int64) (out *gfP) { 11 | if x >= 0 { 12 | out = &gfP{uint64(x)} 13 | } else { 14 | out = &gfP{uint64(-x)} 15 | gfpNeg(out, out) 16 | } 17 | 18 | montEncode(out, out) 19 | return out 20 | } 21 | 22 | func (e *gfP) String() string { 23 | return fmt.Sprintf("%16.16x%16.16x%16.16x%16.16x", e[3], e[2], e[1], e[0]) 24 | } 25 | 26 | func (e *gfP) Set(f *gfP) { 27 | e[0] = f[0] 28 | e[1] = f[1] 29 | e[2] = f[2] 30 | e[3] = f[3] 31 | } 32 | 33 | func (e *gfP) Invert(f *gfP) { 34 | bits := [4]uint64{0x3c208c16d87cfd45, 0x97816a916871ca8d, 0xb85045b68181585d, 0x30644e72e131a029} 35 | 36 | sum, power := &gfP{}, &gfP{} 37 | sum.Set(rN1) 38 | power.Set(f) 39 | 40 | for word := 0; word < 4; word++ { 41 | for bit := uint(0); bit < 64; bit++ { 42 | if (bits[word]>>bit)&1 == 1 { 43 | gfpMul(sum, sum, power) 44 | } 45 | gfpMul(power, power, power) 46 | } 47 | } 48 | 49 | gfpMul(sum, sum, r3) 50 | e.Set(sum) 51 | } 52 | 53 | func (e *gfP) Marshal(out []byte) { 54 | for w := uint(0); w < 4; w++ { 55 | for b := uint(0); b < 8; b++ { 56 | out[8*w+b] = byte(e[3-w] >> (56 - 8*b)) 57 | } 58 | } 59 | } 60 | 61 | func (e *gfP) Unmarshal(in []byte) error { 62 | // Unmarshal the bytes into little endian form 63 | for w := uint(0); w < 4; w++ { 64 | for b := uint(0); b < 8; b++ { 65 | e[3-w] += uint64(in[8*w+b]) << (56 - 8*b) 66 | } 67 | } 68 | // Ensure the point respects the curve modulus 69 | for i := 3; i >= 0; i-- { 70 | if e[i] < p2[i] { 71 | return nil 72 | } 73 | if e[i] > p2[i] { 74 | return errors.New("bn256: coordinate exceeds modulus") 75 | } 76 | } 77 | return errors.New("bn256: coordinate equals modulus") 78 | } 79 | 80 | func montEncode(c, a *gfP) { gfpMul(c, a, r2) } 81 | func montDecode(c, a *gfP) { gfpMul(c, a, &gfP{1}) } 82 | -------------------------------------------------------------------------------- /crypto/bn256/cloudflare/gfp_decl.go: -------------------------------------------------------------------------------- 1 | // +build amd64,!generic arm64,!generic 2 | 3 | package bn256 4 | 5 | // This file contains forward declarations for the architecture-specific 6 | // assembly implementations of these functions, provided that they exist. 7 | 8 | // go:noescape 9 | func gfpNeg(c, a *gfP) 10 | 11 | //go:noescape 12 | func gfpAdd(c, a, b *gfP) 13 | 14 | //go:noescape 15 | func gfpSub(c, a, b *gfP) 16 | 17 | //go:noescape 18 | func gfpMul(c, a, b *gfP) 19 | -------------------------------------------------------------------------------- /crypto/bn256/cloudflare/lattice_test.go: -------------------------------------------------------------------------------- 1 | package bn256 2 | 3 | import ( 4 | "crypto/rand" 5 | 6 | "testing" 7 | ) 8 | 9 | func TestLatticeReduceCurve(t *testing.T) { 10 | k, _ := rand.Int(rand.Reader, Order) 11 | ks := curveLattice.decompose(k) 12 | 13 | if ks[0].BitLen() > 130 || ks[1].BitLen() > 130 { 14 | t.Fatal("reduction too large") 15 | } else if ks[0].Sign() < 0 || ks[1].Sign() < 0 { 16 | t.Fatal("reduction must be positive") 17 | } 18 | } 19 | 20 | func TestLatticeReduceTarget(t *testing.T) { 21 | k, _ := rand.Int(rand.Reader, Order) 22 | ks := targetLattice.decompose(k) 23 | 24 | if ks[0].BitLen() > 66 || ks[1].BitLen() > 66 || ks[2].BitLen() > 66 || ks[3].BitLen() > 66 { 25 | t.Fatal("reduction too large") 26 | } else if ks[0].Sign() < 0 || ks[1].Sign() < 0 || ks[2].Sign() < 0 || ks[3].Sign() < 0 { 27 | t.Fatal("reduction must be positive") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /crypto/bn256/google/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package bn256 6 | 7 | import ( 8 | "crypto/rand" 9 | ) 10 | 11 | func ExamplePair() { 12 | // This implements the tripartite Diffie-Hellman algorithm from "A One 13 | // Round Protocol for Tripartite Diffie-Hellman", A. Joux. 14 | // http://www.springerlink.com/content/cddc57yyva0hburb/fulltext.pdf 15 | 16 | // Each of three parties, a, b and c, generate a private value. 17 | a, _ := rand.Int(rand.Reader, Order) 18 | b, _ := rand.Int(rand.Reader, Order) 19 | c, _ := rand.Int(rand.Reader, Order) 20 | 21 | // Then each party calculates g₁ and g₂ times their private value. 22 | pa := new(G1).ScalarBaseMult(a) 23 | qa := new(G2).ScalarBaseMult(a) 24 | 25 | pb := new(G1).ScalarBaseMult(b) 26 | qb := new(G2).ScalarBaseMult(b) 27 | 28 | pc := new(G1).ScalarBaseMult(c) 29 | qc := new(G2).ScalarBaseMult(c) 30 | 31 | // Now each party exchanges its public values with the other two and 32 | // all parties can calculate the shared key. 33 | k1 := Pair(pb, qc) 34 | k1.ScalarMult(k1, a) 35 | 36 | k2 := Pair(pc, qa) 37 | k2.ScalarMult(k2, b) 38 | 39 | k3 := Pair(pa, qb) 40 | k3.ScalarMult(k3, c) 41 | 42 | // k1, k2 and k3 will all be equal. 43 | } 44 | -------------------------------------------------------------------------------- /crypto/ecies/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | *~ 25 | -------------------------------------------------------------------------------- /crypto/ecies/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Kyle Isom 2 | Copyright (c) 2012 The Go Authors. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above 11 | copyright notice, this list of conditions and the following disclaimer 12 | in the documentation and/or other materials provided with the 13 | distribution. 14 | * Neither the name of Google Inc. nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /crypto/randentropy/rand_entropy.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package randentropy 18 | 19 | import ( 20 | crand "crypto/rand" 21 | "io" 22 | ) 23 | 24 | var Reader io.Reader = &randEntropy{} 25 | 26 | type randEntropy struct { 27 | } 28 | 29 | func (*randEntropy) Read(bytes []byte) (n int, err error) { 30 | readBytes := GetEntropyCSPRNG(len(bytes)) 31 | copy(bytes, readBytes) 32 | return len(bytes), nil 33 | } 34 | 35 | func GetEntropyCSPRNG(n int) []byte { 36 | mainBuff := make([]byte, n) 37 | _, err := io.ReadFull(crand.Reader, mainBuff) 38 | if err != nil { 39 | panic("reading from crypto/rand failed: " + err.Error()) 40 | } 41 | return mainBuff 42 | } 43 | -------------------------------------------------------------------------------- /crypto/secp256k1/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | *~ 25 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/.gitignore: -------------------------------------------------------------------------------- 1 | bench_inv 2 | bench_ecdh 3 | bench_sign 4 | bench_verify 5 | bench_schnorr_verify 6 | bench_recover 7 | bench_internal 8 | tests 9 | exhaustive_tests 10 | gen_context 11 | *.exe 12 | *.so 13 | *.a 14 | !.gitignore 15 | 16 | Makefile 17 | configure 18 | .libs/ 19 | Makefile.in 20 | aclocal.m4 21 | autom4te.cache/ 22 | config.log 23 | config.status 24 | *.tar.gz 25 | *.la 26 | libtool 27 | .deps/ 28 | .dirstamp 29 | *.lo 30 | *.o 31 | *~ 32 | src/libsecp256k1-config.h 33 | src/libsecp256k1-config.h.in 34 | src/ecmult_static_context.h 35 | build-aux/config.guess 36 | build-aux/config.sub 37 | build-aux/depcomp 38 | build-aux/install-sh 39 | build-aux/ltmain.sh 40 | build-aux/m4/libtool.m4 41 | build-aux/m4/lt~obsolete.m4 42 | build-aux/m4/ltoptions.m4 43 | build-aux/m4/ltsugar.m4 44 | build-aux/m4/ltversion.m4 45 | build-aux/missing 46 | build-aux/compile 47 | build-aux/test-driver 48 | src/stamp-h1 49 | libsecp256k1.pc 50 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Pieter Wuille 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/TODO: -------------------------------------------------------------------------------- 1 | * Unit tests for fieldelem/groupelem, including ones intended to 2 | trigger fieldelem's boundary cases. 3 | * Complete constant-time operations for signing/keygen 4 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/autogen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | autoreconf -if --warnings=all 4 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/include/secp256k1_ecdh.h: -------------------------------------------------------------------------------- 1 | #ifndef _SECP256K1_ECDH_ 2 | # define _SECP256K1_ECDH_ 3 | 4 | # include "secp256k1.h" 5 | 6 | # ifdef __cplusplus 7 | extern "C" { 8 | # endif 9 | 10 | /** Compute an EC Diffie-Hellman secret in constant time 11 | * Returns: 1: exponentiation was successful 12 | * 0: scalar was invalid (zero or overflow) 13 | * Args: ctx: pointer to a context object (cannot be NULL) 14 | * Out: result: a 32-byte array which will be populated by an ECDH 15 | * secret computed from the point and scalar 16 | * In: pubkey: a pointer to a secp256k1_pubkey containing an 17 | * initialized public key 18 | * privkey: a 32-byte scalar with which to multiply the point 19 | */ 20 | SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdh( 21 | const secp256k1_context* ctx, 22 | unsigned char *result, 23 | const secp256k1_pubkey *pubkey, 24 | const unsigned char *privkey 25 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); 26 | 27 | # ifdef __cplusplus 28 | } 29 | # endif 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/libsecp256k1.pc.in: -------------------------------------------------------------------------------- 1 | prefix=@prefix@ 2 | exec_prefix=@exec_prefix@ 3 | libdir=@libdir@ 4 | includedir=@includedir@ 5 | 6 | Name: libsecp256k1 7 | Description: Optimized C library for EC operations on curve secp256k1 8 | URL: https://github.com/bitcoin-core/secp256k1 9 | Version: @PACKAGE_VERSION@ 10 | Cflags: -I${includedir} 11 | Libs.private: @SECP_LIBS@ 12 | Libs: -L${libdir} -lsecp256k1 13 | 14 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/obj/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/crypto/secp256k1/libsecp256k1/obj/.gitignore -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/basic-config.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_BASIC_CONFIG_ 8 | #define _SECP256K1_BASIC_CONFIG_ 9 | 10 | #ifdef USE_BASIC_CONFIG 11 | 12 | #undef USE_ASM_X86_64 13 | #undef USE_ENDOMORPHISM 14 | #undef USE_FIELD_10X26 15 | #undef USE_FIELD_5X52 16 | #undef USE_FIELD_INV_BUILTIN 17 | #undef USE_FIELD_INV_NUM 18 | #undef USE_NUM_GMP 19 | #undef USE_NUM_NONE 20 | #undef USE_SCALAR_4X64 21 | #undef USE_SCALAR_8X32 22 | #undef USE_SCALAR_INV_BUILTIN 23 | #undef USE_SCALAR_INV_NUM 24 | 25 | #define USE_NUM_NONE 1 26 | #define USE_FIELD_INV_BUILTIN 1 27 | #define USE_SCALAR_INV_BUILTIN 1 28 | #define USE_FIELD_10X26 1 29 | #define USE_SCALAR_8X32 1 30 | 31 | #endif // USE_BASIC_CONFIG 32 | #endif // _SECP256K1_BASIC_CONFIG_ 33 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/bench_ecdh.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | 9 | #include "include/secp256k1.h" 10 | #include "include/secp256k1_ecdh.h" 11 | #include "util.h" 12 | #include "bench.h" 13 | 14 | typedef struct { 15 | secp256k1_context *ctx; 16 | secp256k1_pubkey point; 17 | unsigned char scalar[32]; 18 | } bench_ecdh_t; 19 | 20 | static void bench_ecdh_setup(void* arg) { 21 | int i; 22 | bench_ecdh_t *data = (bench_ecdh_t*)arg; 23 | const unsigned char point[] = { 24 | 0x03, 25 | 0x54, 0x94, 0xc1, 0x5d, 0x32, 0x09, 0x97, 0x06, 26 | 0xc2, 0x39, 0x5f, 0x94, 0x34, 0x87, 0x45, 0xfd, 27 | 0x75, 0x7c, 0xe3, 0x0e, 0x4e, 0x8c, 0x90, 0xfb, 28 | 0xa2, 0xba, 0xd1, 0x84, 0xf8, 0x83, 0xc6, 0x9f 29 | }; 30 | 31 | /* create a context with no capabilities */ 32 | data->ctx = secp256k1_context_create(SECP256K1_FLAGS_TYPE_CONTEXT); 33 | for (i = 0; i < 32; i++) { 34 | data->scalar[i] = i + 1; 35 | } 36 | CHECK(secp256k1_ec_pubkey_parse(data->ctx, &data->point, point, sizeof(point)) == 1); 37 | } 38 | 39 | static void bench_ecdh(void* arg) { 40 | int i; 41 | unsigned char res[32]; 42 | bench_ecdh_t *data = (bench_ecdh_t*)arg; 43 | 44 | for (i = 0; i < 20000; i++) { 45 | CHECK(secp256k1_ecdh(data->ctx, res, &data->point, data->scalar) == 1); 46 | } 47 | } 48 | 49 | int main(void) { 50 | bench_ecdh_t data; 51 | 52 | run_benchmark("ecdh", bench_ecdh, bench_ecdh_setup, NULL, &data, 10, 20000); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/bench_sign.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include "include/secp256k1.h" 8 | #include "util.h" 9 | #include "bench.h" 10 | 11 | typedef struct { 12 | secp256k1_context* ctx; 13 | unsigned char msg[32]; 14 | unsigned char key[32]; 15 | } bench_sign_t; 16 | 17 | static void bench_sign_setup(void* arg) { 18 | int i; 19 | bench_sign_t *data = (bench_sign_t*)arg; 20 | 21 | for (i = 0; i < 32; i++) { 22 | data->msg[i] = i + 1; 23 | } 24 | for (i = 0; i < 32; i++) { 25 | data->key[i] = i + 65; 26 | } 27 | } 28 | 29 | static void bench_sign(void* arg) { 30 | int i; 31 | bench_sign_t *data = (bench_sign_t*)arg; 32 | 33 | unsigned char sig[74]; 34 | for (i = 0; i < 20000; i++) { 35 | size_t siglen = 74; 36 | int j; 37 | secp256k1_ecdsa_signature signature; 38 | CHECK(secp256k1_ecdsa_sign(data->ctx, &signature, data->msg, data->key, NULL, NULL)); 39 | CHECK(secp256k1_ecdsa_signature_serialize_der(data->ctx, sig, &siglen, &signature)); 40 | for (j = 0; j < 32; j++) { 41 | data->msg[j] = sig[j]; 42 | data->key[j] = sig[j + 32]; 43 | } 44 | } 45 | } 46 | 47 | int main(void) { 48 | bench_sign_t data; 49 | 50 | data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); 51 | 52 | run_benchmark("ecdsa_sign", bench_sign, bench_sign_setup, NULL, &data, 10, 20000); 53 | 54 | secp256k1_context_destroy(data.ctx); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/ecdsa.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECDSA_ 8 | #define _SECP256K1_ECDSA_ 9 | 10 | #include 11 | 12 | #include "scalar.h" 13 | #include "group.h" 14 | #include "ecmult.h" 15 | 16 | static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *r, secp256k1_scalar *s, const unsigned char *sig, size_t size); 17 | static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar *r, const secp256k1_scalar *s); 18 | static int secp256k1_ecdsa_sig_verify(const secp256k1_ecmult_context *ctx, const secp256k1_scalar* r, const secp256k1_scalar* s, const secp256k1_ge *pubkey, const secp256k1_scalar *message); 19 | static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/eckey.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECKEY_ 8 | #define _SECP256K1_ECKEY_ 9 | 10 | #include 11 | 12 | #include "group.h" 13 | #include "scalar.h" 14 | #include "ecmult.h" 15 | #include "ecmult_gen.h" 16 | 17 | static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size); 18 | static int secp256k1_eckey_pubkey_serialize(secp256k1_ge *elem, unsigned char *pub, size_t *size, int compressed); 19 | 20 | static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak); 21 | static int secp256k1_eckey_pubkey_tweak_add(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); 22 | static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak); 23 | static int secp256k1_eckey_pubkey_tweak_mul(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/ecmult.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_ 8 | #define _SECP256K1_ECMULT_ 9 | 10 | #include "num.h" 11 | #include "group.h" 12 | 13 | typedef struct { 14 | /* For accelerating the computation of a*P + b*G: */ 15 | secp256k1_ge_storage (*pre_g)[]; /* odd multiples of the generator */ 16 | #ifdef USE_ENDOMORPHISM 17 | secp256k1_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */ 18 | #endif 19 | } secp256k1_ecmult_context; 20 | 21 | static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx); 22 | static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb); 23 | static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, 24 | const secp256k1_ecmult_context *src, const secp256k1_callback *cb); 25 | static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx); 26 | static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx); 27 | 28 | /** Double multiply: R = na*A + ng*G */ 29 | static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/ecmult_const.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_CONST_ 8 | #define _SECP256K1_ECMULT_CONST_ 9 | 10 | #include "scalar.h" 11 | #include "group.h" 12 | 13 | static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/field_5x52.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_FIELD_REPR_ 8 | #define _SECP256K1_FIELD_REPR_ 9 | 10 | #include 11 | 12 | typedef struct { 13 | /* X = sum(i=0..4, elem[i]*2^52) mod n */ 14 | uint64_t n[5]; 15 | #ifdef VERIFY 16 | int magnitude; 17 | int normalized; 18 | #endif 19 | } secp256k1_fe; 20 | 21 | /* Unpacks a constant into a overlapping multi-limbed FE element. */ 22 | #define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ 23 | (d0) | (((uint64_t)(d1) & 0xFFFFFUL) << 32), \ 24 | ((uint64_t)(d1) >> 20) | (((uint64_t)(d2)) << 12) | (((uint64_t)(d3) & 0xFFUL) << 44), \ 25 | ((uint64_t)(d3) >> 8) | (((uint64_t)(d4) & 0xFFFFFFFUL) << 24), \ 26 | ((uint64_t)(d4) >> 28) | (((uint64_t)(d5)) << 4) | (((uint64_t)(d6) & 0xFFFFUL) << 36), \ 27 | ((uint64_t)(d6) >> 16) | (((uint64_t)(d7)) << 16) \ 28 | } 29 | 30 | #ifdef VERIFY 31 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} 32 | #else 33 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} 34 | #endif 35 | 36 | typedef struct { 37 | uint64_t n[4]; 38 | } secp256k1_fe_storage; 39 | 40 | #define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ \ 41 | (d0) | (((uint64_t)(d1)) << 32), \ 42 | (d2) | (((uint64_t)(d3)) << 32), \ 43 | (d4) | (((uint64_t)(d5)) << 32), \ 44 | (d6) | (((uint64_t)(d7)) << 32) \ 45 | }} 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/hash.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_HASH_ 8 | #define _SECP256K1_HASH_ 9 | 10 | #include 11 | #include 12 | 13 | typedef struct { 14 | uint32_t s[8]; 15 | uint32_t buf[16]; /* In big endian */ 16 | size_t bytes; 17 | } secp256k1_sha256_t; 18 | 19 | static void secp256k1_sha256_initialize(secp256k1_sha256_t *hash); 20 | static void secp256k1_sha256_write(secp256k1_sha256_t *hash, const unsigned char *data, size_t size); 21 | static void secp256k1_sha256_finalize(secp256k1_sha256_t *hash, unsigned char *out32); 22 | 23 | typedef struct { 24 | secp256k1_sha256_t inner, outer; 25 | } secp256k1_hmac_sha256_t; 26 | 27 | static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256_t *hash, const unsigned char *key, size_t size); 28 | static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256_t *hash, const unsigned char *data, size_t size); 29 | static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256_t *hash, unsigned char *out32); 30 | 31 | typedef struct { 32 | unsigned char v[32]; 33 | unsigned char k[32]; 34 | int retry; 35 | } secp256k1_rfc6979_hmac_sha256_t; 36 | 37 | static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256_t *rng, const unsigned char *key, size_t keylen); 38 | static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256_t *rng, unsigned char *out, size_t outlen); 39 | static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256_t *rng); 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/NativeSecp256k1Util.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2016 the libsecp256k1 contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.bitcoin; 18 | 19 | public class NativeSecp256k1Util{ 20 | 21 | public static void assertEquals( int val, int val2, String message ) throws AssertFailException{ 22 | if( val != val2 ) 23 | throw new AssertFailException("FAIL: " + message); 24 | } 25 | 26 | public static void assertEquals( boolean val, boolean val2, String message ) throws AssertFailException{ 27 | if( val != val2 ) 28 | throw new AssertFailException("FAIL: " + message); 29 | else 30 | System.out.println("PASS: " + message); 31 | } 32 | 33 | public static void assertEquals( String val, String val2, String message ) throws AssertFailException{ 34 | if( !val.equals(val2) ) 35 | throw new AssertFailException("FAIL: " + message); 36 | else 37 | System.out.println("PASS: " + message); 38 | } 39 | 40 | public static class AssertFailException extends Exception { 41 | public AssertFailException(String message) { 42 | super( message ); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/Secp256k1Context.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2016 the libsecp256k1 contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.bitcoin; 18 | 19 | /** 20 | * This class holds the context reference used in native methods 21 | * to handle ECDSA operations. 22 | */ 23 | public class Secp256k1Context { 24 | private static final boolean enabled; //true if the library is loaded 25 | private static final long context; //ref to pointer to context obj 26 | 27 | static { //static initializer 28 | boolean isEnabled = true; 29 | long contextRef = -1; 30 | try { 31 | System.loadLibrary("secp256k1"); 32 | contextRef = secp256k1_init_context(); 33 | } catch (UnsatisfiedLinkError e) { 34 | System.out.println("UnsatisfiedLinkError: " + e.toString()); 35 | isEnabled = false; 36 | } 37 | enabled = isEnabled; 38 | context = contextRef; 39 | } 40 | 41 | public static boolean isEnabled() { 42 | return enabled; 43 | } 44 | 45 | public static long getContext() { 46 | if(!enabled) return -1; //sanity check 47 | return context; 48 | } 49 | 50 | private static native long secp256k1_init_context(); 51 | } 52 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/java/org_bitcoin_Secp256k1Context.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "org_bitcoin_Secp256k1Context.h" 4 | #include "include/secp256k1.h" 5 | 6 | SECP256K1_API jlong JNICALL Java_org_bitcoin_Secp256k1Context_secp256k1_1init_1context 7 | (JNIEnv* env, jclass classObject) 8 | { 9 | secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); 10 | 11 | (void)classObject;(void)env; 12 | 13 | return (uintptr_t)ctx; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/java/org_bitcoin_Secp256k1Context.h: -------------------------------------------------------------------------------- 1 | /* DO NOT EDIT THIS FILE - it is machine generated */ 2 | #include 3 | #include "include/secp256k1.h" 4 | /* Header for class org_bitcoin_Secp256k1Context */ 5 | 6 | #ifndef _Included_org_bitcoin_Secp256k1Context 7 | #define _Included_org_bitcoin_Secp256k1Context 8 | #ifdef __cplusplus 9 | extern "C" { 10 | #endif 11 | /* 12 | * Class: org_bitcoin_Secp256k1Context 13 | * Method: secp256k1_init_context 14 | * Signature: ()J 15 | */ 16 | SECP256K1_API jlong JNICALL Java_org_bitcoin_Secp256k1Context_secp256k1_1init_1context 17 | (JNIEnv *, jclass); 18 | 19 | #ifdef __cplusplus 20 | } 21 | #endif 22 | #endif 23 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/modules/ecdh/Makefile.am.include: -------------------------------------------------------------------------------- 1 | include_HEADERS += include/secp256k1_ecdh.h 2 | noinst_HEADERS += src/modules/ecdh/main_impl.h 3 | noinst_HEADERS += src/modules/ecdh/tests_impl.h 4 | if USE_BENCHMARK 5 | noinst_PROGRAMS += bench_ecdh 6 | bench_ecdh_SOURCES = src/bench_ecdh.c 7 | bench_ecdh_LDADD = libsecp256k1.la $(SECP_LIBS) $(COMMON_LIB) 8 | endif 9 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/modules/recovery/Makefile.am.include: -------------------------------------------------------------------------------- 1 | include_HEADERS += include/secp256k1_recovery.h 2 | noinst_HEADERS += src/modules/recovery/main_impl.h 3 | noinst_HEADERS += src/modules/recovery/tests_impl.h 4 | if USE_BENCHMARK 5 | noinst_PROGRAMS += bench_recover 6 | bench_recover_SOURCES = src/bench_recover.c 7 | bench_recover_LDADD = libsecp256k1.la $(SECP_LIBS) $(COMMON_LIB) 8 | endif 9 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/num_gmp.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_NUM_REPR_ 8 | #define _SECP256K1_NUM_REPR_ 9 | 10 | #include 11 | 12 | #define NUM_LIMBS ((256+GMP_NUMB_BITS-1)/GMP_NUMB_BITS) 13 | 14 | typedef struct { 15 | mp_limb_t data[2*NUM_LIMBS]; 16 | int neg; 17 | int limbs; 18 | } secp256k1_num; 19 | 20 | #endif 21 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/num_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_NUM_IMPL_H_ 8 | #define _SECP256K1_NUM_IMPL_H_ 9 | 10 | #if defined HAVE_CONFIG_H 11 | #include "libsecp256k1-config.h" 12 | #endif 13 | 14 | #include "num.h" 15 | 16 | #if defined(USE_NUM_GMP) 17 | #include "num_gmp_impl.h" 18 | #elif defined(USE_NUM_NONE) 19 | /* Nothing. */ 20 | #else 21 | #error "Please select num implementation" 22 | #endif 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/scalar_4x64.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef struct { 14 | uint64_t d[4]; 15 | } secp256k1_scalar; 16 | 17 | #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/scalar_8x32.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef struct { 14 | uint32_t d[8]; 15 | } secp256k1_scalar; 16 | 17 | #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/scalar_low.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef uint32_t secp256k1_scalar; 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /crypto/secp256k1/libsecp256k1/src/testrand.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_TESTRAND_H_ 8 | #define _SECP256K1_TESTRAND_H_ 9 | 10 | #if defined HAVE_CONFIG_H 11 | #include "libsecp256k1-config.h" 12 | #endif 13 | 14 | /* A non-cryptographic RNG used only for test infrastructure. */ 15 | 16 | /** Seed the pseudorandom number generator for testing. */ 17 | SECP256K1_INLINE static void secp256k1_rand_seed(const unsigned char *seed16); 18 | 19 | /** Generate a pseudorandom number in the range [0..2**32-1]. */ 20 | static uint32_t secp256k1_rand32(void); 21 | 22 | /** Generate a pseudorandom number in the range [0..2**bits-1]. Bits must be 1 or 23 | * more. */ 24 | static uint32_t secp256k1_rand_bits(int bits); 25 | 26 | /** Generate a pseudorandom number in the range [0..range-1]. */ 27 | static uint32_t secp256k1_rand_int(uint32_t range); 28 | 29 | /** Generate a pseudorandom 32-byte array. */ 30 | static void secp256k1_rand256(unsigned char *b32); 31 | 32 | /** Generate a pseudorandom 32-byte array with long sequences of zero and one bits. */ 33 | static void secp256k1_rand256_test(unsigned char *b32); 34 | 35 | /** Generate pseudorandom bytes with long sequences of zero and one bits. */ 36 | static void secp256k1_rand_bytes_test(unsigned char *bytes, size_t len); 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /crypto/secp256k1/panic_cb.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package secp256k1 18 | 19 | import "C" 20 | import "unsafe" 21 | 22 | // Callbacks for converting libsecp256k1 internal faults into 23 | // recoverable Go panics. 24 | 25 | //export secp256k1GoPanicIllegal 26 | func secp256k1GoPanicIllegal(msg *C.char, data unsafe.Pointer) { 27 | panic("illegal argument: " + C.GoString(msg)) 28 | } 29 | 30 | //export secp256k1GoPanicError 31 | func secp256k1GoPanicError(msg *C.char, data unsafe.Pointer) { 32 | panic("internal error: " + C.GoString(msg)) 33 | } 34 | -------------------------------------------------------------------------------- /crypto/sha3/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /crypto/sha3/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /crypto/sha3/keccakf_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64,!appengine,!gccgo 6 | 7 | package sha3 8 | 9 | // This function is implemented in keccakf_amd64.s. 10 | 11 | //go:noescape 12 | 13 | func keccakF1600(state *[25]uint64) 14 | -------------------------------------------------------------------------------- /crypto/sha3/register.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.4 6 | 7 | package sha3 8 | 9 | import ( 10 | "crypto" 11 | ) 12 | 13 | func init() { 14 | crypto.RegisterHash(crypto.SHA3_224, New224) 15 | crypto.RegisterHash(crypto.SHA3_256, New256) 16 | crypto.RegisterHash(crypto.SHA3_384, New384) 17 | crypto.RegisterHash(crypto.SHA3_512, New512) 18 | } 19 | -------------------------------------------------------------------------------- /crypto/sha3/testdata/keccakKats.json.deflate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/crypto/sha3/testdata/keccakKats.json.deflate -------------------------------------------------------------------------------- /crypto/sha3/xor.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !amd64,!386,!ppc64le appengine 6 | 7 | package sha3 8 | 9 | var ( 10 | xorIn = xorInGeneric 11 | copyOut = copyOutGeneric 12 | xorInUnaligned = xorInGeneric 13 | copyOutUnaligned = copyOutGeneric 14 | ) 15 | 16 | const xorImplementationUnaligned = "generic" 17 | -------------------------------------------------------------------------------- /crypto/sha3/xor_generic.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package sha3 6 | 7 | import "encoding/binary" 8 | 9 | // xorInGeneric xors the bytes in buf into the state; it 10 | // makes no non-portable assumptions about memory layout 11 | // or alignment. 12 | func xorInGeneric(d *state, buf []byte) { 13 | n := len(buf) / 8 14 | 15 | for i := 0; i < n; i++ { 16 | a := binary.LittleEndian.Uint64(buf) 17 | d.a[i] ^= a 18 | buf = buf[8:] 19 | } 20 | } 21 | 22 | // copyOutGeneric copies ulint64s to a byte buffer. 23 | func copyOutGeneric(d *state, b []byte) { 24 | for i := 0; len(b) >= 8; i++ { 25 | binary.LittleEndian.PutUint64(b, d.a[i]) 26 | b = b[8:] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /crypto/sha3/xor_unaligned.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64 386 ppc64le 6 | // +build !appengine 7 | 8 | package sha3 9 | 10 | import "unsafe" 11 | 12 | func xorInUnaligned(d *state, buf []byte) { 13 | bw := (*[maxRate / 8]uint64)(unsafe.Pointer(&buf[0])) 14 | n := len(buf) 15 | if n >= 72 { 16 | d.a[0] ^= bw[0] 17 | d.a[1] ^= bw[1] 18 | d.a[2] ^= bw[2] 19 | d.a[3] ^= bw[3] 20 | d.a[4] ^= bw[4] 21 | d.a[5] ^= bw[5] 22 | d.a[6] ^= bw[6] 23 | d.a[7] ^= bw[7] 24 | d.a[8] ^= bw[8] 25 | } 26 | if n >= 104 { 27 | d.a[9] ^= bw[9] 28 | d.a[10] ^= bw[10] 29 | d.a[11] ^= bw[11] 30 | d.a[12] ^= bw[12] 31 | } 32 | if n >= 136 { 33 | d.a[13] ^= bw[13] 34 | d.a[14] ^= bw[14] 35 | d.a[15] ^= bw[15] 36 | d.a[16] ^= bw[16] 37 | } 38 | if n >= 144 { 39 | d.a[17] ^= bw[17] 40 | } 41 | if n >= 168 { 42 | d.a[18] ^= bw[18] 43 | d.a[19] ^= bw[19] 44 | d.a[20] ^= bw[20] 45 | } 46 | } 47 | 48 | func copyOutUnaligned(d *state, buf []byte) { 49 | ab := (*[maxRate]uint8)(unsafe.Pointer(&d.a[0])) 50 | copy(buf, ab[:]) 51 | } 52 | 53 | var ( 54 | xorIn = xorInUnaligned 55 | copyOut = copyOutUnaligned 56 | ) 57 | 58 | const xorImplementationUnaligned = "unaligned" 59 | -------------------------------------------------------------------------------- /db/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile ~/.gitignore_global 6 | 7 | /tmp 8 | */**/*un~ 9 | *un~ 10 | .DS_Store 11 | */**/.DS_Store 12 | 13 | -------------------------------------------------------------------------------- /db/interface.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package ethdb 18 | 19 | // Code using batches should try to add this much data to the batch. 20 | // The value was determined empirically. 21 | const IdealBatchSize = 100 * 1024 22 | 23 | // Putter wraps the database write operation supported by both batches and regular databases. 24 | type Putter interface { 25 | Put(key []byte, value []byte) error 26 | } 27 | 28 | // Database wraps all database operations. All methods are safe for concurrent use. 29 | type Database interface { 30 | Putter 31 | Get(key []byte) ([]byte, error) 32 | Has(key []byte) (bool, error) 33 | Delete(key []byte) error 34 | Close() 35 | NewBatch() Batch 36 | } 37 | 38 | // Batch is a write-only database that commits changes to its host database 39 | // when Write is called. Batch cannot be used concurrently. 40 | type Batch interface { 41 | Putter 42 | ValueSize() int // amount of data in the batch 43 | Write() error 44 | // Reset resets the batch for reuse 45 | Reset() 46 | } 47 | -------------------------------------------------------------------------------- /event/example_subscription_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package event_test 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/cypherium_private/mvp/event" 23 | ) 24 | 25 | func ExampleNewSubscription() { 26 | // Create a subscription that sends 10 integers on ch. 27 | ch := make(chan int) 28 | sub := event.NewSubscription(func(quit <-chan struct{}) error { 29 | for i := 0; i < 10; i++ { 30 | select { 31 | case ch <- i: 32 | case <-quit: 33 | fmt.Println("unsubscribed") 34 | return nil 35 | } 36 | } 37 | return nil 38 | }) 39 | 40 | // This is the consumer. It reads 5 integers, then aborts the subscription. 41 | // Note that Unsubscribe waits until the producer has shut down. 42 | for i := range ch { 43 | fmt.Println(i) 44 | if i == 4 { 45 | sub.Unsubscribe() 46 | break 47 | } 48 | } 49 | // Output: 50 | // 0 51 | // 1 52 | // 2 53 | // 3 54 | // 4 55 | // unsubscribed 56 | } 57 | -------------------------------------------------------------------------------- /event/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package event 18 | 19 | import "fmt" 20 | 21 | func ExampleTypeMux() { 22 | type someEvent struct{ I int } 23 | type otherEvent struct{ S string } 24 | type yetAnotherEvent struct{ X, Y int } 25 | 26 | var mux TypeMux 27 | 28 | // Start a subscriber. 29 | done := make(chan struct{}) 30 | sub := mux.Subscribe(someEvent{}, otherEvent{}) 31 | go func() { 32 | for event := range sub.Chan() { 33 | fmt.Printf("Received: %#v\n", event.Data) 34 | } 35 | fmt.Println("done") 36 | close(done) 37 | }() 38 | 39 | // Post some events. 40 | mux.Post(someEvent{5}) 41 | mux.Post(yetAnotherEvent{X: 3, Y: 4}) 42 | mux.Post(someEvent{6}) 43 | mux.Post(otherEvent{"whoa"}) 44 | 45 | // Stop closes all subscription channels. 46 | // The subscriber goroutine will print "done" 47 | // and exit. 48 | mux.Stop() 49 | 50 | // Wait for subscriber to return. 51 | <-done 52 | 53 | // Output: 54 | // Received: event.someEvent{I:5} 55 | // Received: event.someEvent{I:6} 56 | // Received: event.otherEvent{S:"whoa"} 57 | // done 58 | } 59 | -------------------------------------------------------------------------------- /event/filter/filter_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package filter 18 | 19 | import ( 20 | "testing" 21 | "time" 22 | ) 23 | 24 | // Simple test to check if baseline matching/mismatching filtering works. 25 | func TestFilters(t *testing.T) { 26 | fm := New() 27 | fm.Start() 28 | 29 | // Register two filters to catch posted data 30 | first := make(chan struct{}) 31 | fm.Install(Generic{ 32 | Str1: "hello", 33 | Fn: func(data interface{}) { 34 | first <- struct{}{} 35 | }, 36 | }) 37 | second := make(chan struct{}) 38 | fm.Install(Generic{ 39 | Str1: "hello1", 40 | Str2: "hello", 41 | Fn: func(data interface{}) { 42 | second <- struct{}{} 43 | }, 44 | }) 45 | // Post an event that should only match the first filter 46 | fm.Notify(Generic{Str1: "hello"}, true) 47 | fm.Stop() 48 | 49 | // Ensure only the mathcing filters fire 50 | select { 51 | case <-first: 52 | case <-time.After(100 * time.Millisecond): 53 | t.Error("matching filter timed out") 54 | } 55 | select { 56 | case <-second: 57 | t.Error("mismatching filter fired") 58 | case <-time.After(100 * time.Millisecond): 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /event/filter/generic_filter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package filter 18 | 19 | type Generic struct { 20 | Str1, Str2, Str3 string 21 | Data map[string]struct{} 22 | 23 | Fn func(data interface{}) 24 | } 25 | 26 | // self = registered, f = incoming 27 | func (self Generic) Compare(f Filter) bool { 28 | var strMatch, dataMatch = true, true 29 | 30 | filter := f.(Generic) 31 | if (len(self.Str1) > 0 && filter.Str1 != self.Str1) || 32 | (len(self.Str2) > 0 && filter.Str2 != self.Str2) || 33 | (len(self.Str3) > 0 && filter.Str3 != self.Str3) { 34 | strMatch = false 35 | } 36 | 37 | for k := range self.Data { 38 | if _, ok := filter.Data[k]; !ok { 39 | return false 40 | } 41 | } 42 | 43 | return strMatch && dataMatch 44 | } 45 | 46 | func (self Generic) Trigger(data interface{}) { 47 | self.Fn(data) 48 | } 49 | -------------------------------------------------------------------------------- /html/README.md: -------------------------------------------------------------------------------- 1 | # Web-interface to cothority 2 | 3 | The cothority-services can interact using protobuf over websockets with other 4 | languages. This directory shows how to use javascript to interact with 5 | services. 6 | 7 | In `index.html` you can find an example how to contact the service from 8 | javascript. The `js/`-directory has the needed libraries for the communication. 9 | `js/bundle.js` is a compilation of the `src/`-directory where the protobuf- 10 | definitions are stored. 11 | 12 | ## Updating `js/bundle.js` 13 | 14 | If you change the protobuf-files or add new ones, you need to compile them 15 | so they're available under javascript. 16 | The protobuf-files are stored under `src/models/`. if you add a new file, 17 | it will be automatically picked up by the compilation-scipt. 18 | To compile all protobuf-files to `js/bundle.js`, launche the following: 19 | 20 | ```bash 21 | cd src 22 | make 23 | ``` 24 | 25 | This supposes you have `node` and `npm` installed, and will create a new 26 | `js/bundle.js`. 27 | 28 | ## `CothorityMessages` 29 | 30 | The main class in javascript that contains helper-functions for every 31 | method of the service-api. It is not created automatically. So if you 32 | add new proto-files or new messages to it, you need to extend it manually. 33 | The class is defined in `src/index.js` and has some helper methods: 34 | 35 | ### createSocket 36 | 37 | `createSocket` is a simple method to encode javascript-objects using 38 | protobuf and send it through websockets to the service. 39 | 40 | ### toml_to_roster 41 | 42 | Converts a toml-string of public.toml to a roster that can be sent 43 | to a service. Also calculates the Id of the ServerIdentities. 44 | 45 | ### si_to_ws 46 | 47 | Returns a websocket-url from a ServerIdentity. 48 | 49 | -------------------------------------------------------------------------------- /html/css/custom.css: -------------------------------------------------------------------------------- 1 | #main h3 { 2 | font-size: 12pt; 3 | text-transform: none; 4 | letter-spacing: 1px; 5 | } 6 | 7 | #main a { 8 | text-decoration: underline; 9 | } 10 | 11 | #main p { 12 | /*font-size: 12px;*/ 13 | text-transform: none; 14 | letter-spacing: 1px; 15 | } 16 | 17 | .box{ 18 | margin-left: auto; 19 | margin-right: auto; 20 | max-width: 25em; 21 | text-transform: none; 22 | letter-spacing: 1px; 23 | text-align: left; 24 | } 25 | 26 | .box h2 { 27 | text-align: center; 28 | } 29 | 30 | .box a { 31 | text-decoration: underline; 32 | } 33 | 34 | .center { 35 | text-align: center; 36 | } 37 | 38 | .disclaimer { 39 | font-size: 7pt; 40 | max-width: 35em; 41 | } 42 | 43 | pre { 44 | font-family: monospace; 45 | font-size: 12px; 46 | background-color: #f0f0f0; 47 | padding: 10px 0px 10px 20px; 48 | } 49 | 50 | #rand_value pre { 51 | padding: 10px 0px 10px 0px; 52 | } 53 | 54 | textarea { 55 | color: #414f57; 56 | font-family: monospace; 57 | font-size: 12pt; 58 | font-weight: 100; 59 | line-height: 1.1; 60 | letter-spacing: 0em; 61 | text-transform: none; 62 | } 63 | 64 | @media screen and (max-width: 1680px) { 65 | 66 | textarea { 67 | font-size: 11pt; 68 | } 69 | 70 | } 71 | 72 | @media screen and (max-width: 480px) { 73 | 74 | textarea { 75 | font-size: 10pt; 76 | line-height: 1.75; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /html/css/ie8.css: -------------------------------------------------------------------------------- 1 | /* 2 | Identity by HTML5 UP 3 | html5up.net | @ajlkn 4 | Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) 5 | */ 6 | 7 | /* List */ 8 | 9 | ul.icons li a { 10 | -ms-behavior: url("assets/js/PIE.htc"); 11 | } 12 | 13 | ul.icons li a:before { 14 | text-align: center; 15 | font-size: 26px; 16 | } 17 | 18 | /* Main */ 19 | 20 | #main { 21 | -ms-behavior: url("assets/js/PIE.htc"); 22 | } 23 | 24 | #main .avatar img { 25 | -ms-behavior: url("assets/js/PIE.htc"); 26 | } 27 | 28 | /* Footer */ 29 | 30 | #footer { 31 | color: #fff; 32 | } 33 | 34 | #footer .copyright li { 35 | border-left: solid 1px #fff; 36 | } -------------------------------------------------------------------------------- /html/css/ie9.css: -------------------------------------------------------------------------------- 1 | /* 2 | Identity by HTML5 UP 3 | html5up.net | @ajlkn 4 | Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) 5 | */ 6 | 7 | /* Basic */ 8 | 9 | body:after { 10 | display: none; 11 | } 12 | 13 | /* List */ 14 | 15 | ul.icons li a:before { 16 | color: #c8cccf; 17 | } 18 | 19 | ul.icons li a:hover:before { 20 | color: #ff7496; 21 | } 22 | 23 | /* Wrapper */ 24 | 25 | #wrapper { 26 | text-align: center; 27 | } 28 | 29 | /* Main */ 30 | 31 | #main { 32 | display: inline-block; 33 | } -------------------------------------------------------------------------------- /html/css/images/overlay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/css/images/overlay.png -------------------------------------------------------------------------------- /html/css/noscript.css: -------------------------------------------------------------------------------- 1 | /* 2 | Identity by HTML5 UP 3 | html5up.net | @ajlkn 4 | Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) 5 | */ 6 | 7 | /* Basic */ 8 | 9 | body:after { 10 | display: none; 11 | } 12 | 13 | /* Main */ 14 | 15 | #main { 16 | -moz-transform: none !important; 17 | -webkit-transform: none !important; 18 | -ms-transform: none !important; 19 | transform: none !important; 20 | opacity: 1 !important; 21 | } -------------------------------------------------------------------------------- /html/css/progress.css: -------------------------------------------------------------------------------- 1 | #progressbar { 2 | width: 100%; 3 | height: 12px; 4 | background-color: #eee; 5 | padding: 2px; 6 | margin: .6em 0; 7 | border: 1px #000 double; 8 | clear: both; 9 | } 10 | 11 | .progress { 12 | background: #555555; /*-- Color of the bar --*/ 13 | height: 5px; 14 | width: 0%; 15 | max-width: 100%; 16 | float: left; 17 | animation: progress linear 30s 1 forwards; 18 | } 19 | 20 | @keyframes progress { 21 | from { } 22 | 23 | to { width: 100% } 24 | } -------------------------------------------------------------------------------- /html/fonts/FontAwesome.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/fonts/FontAwesome.otf -------------------------------------------------------------------------------- /html/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /html/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /html/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /html/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /html/images/avatar.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/images/avatar.jpg -------------------------------------------------------------------------------- /html/images/bg-old.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/images/bg-old.jpg -------------------------------------------------------------------------------- /html/images/bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/html/images/bg.jpg -------------------------------------------------------------------------------- /html/src/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | test -d node_modules || npm i 3 | node build_proto.js 4 | node build.js 5 | -------------------------------------------------------------------------------- /html/src/build.js: -------------------------------------------------------------------------------- 1 | var rollup = require('rollup'); 2 | var babel = require('rollup-plugin-babel'); 3 | 4 | rollup.rollup({ 5 | entry: 'index.js', 6 | external: ['protobufjs'], 7 | plugins: [ 8 | babel({ 9 | babelrc: false, 10 | presets: [["es2015-rollup"]] 11 | }) 12 | ] 13 | }).then( 14 | (bundle) => { 15 | console.log('write file'); 16 | 17 | bundle.write({ 18 | format: 'iife', 19 | moduleName: 'CothorityProtobuf', 20 | dest: '../js/bundle.js' 21 | }); 22 | }, 23 | (e) => console.log('error', e) 24 | ); 25 | -------------------------------------------------------------------------------- /html/src/build_proto.js: -------------------------------------------------------------------------------- 1 | const protobuf = require('protobufjs'); 2 | const fs = require('fs'); 3 | 4 | const root = new protobuf.Root(); 5 | root.define('cothority'); 6 | 7 | const regex = /^.*\.proto$/; 8 | 9 | fs.readdir('models', (err, items) => { 10 | items.forEach(file => { 11 | if (regex.test(file)) { 12 | root.loadSync('models/' + file); 13 | } 14 | }); 15 | 16 | fs.writeFileSync('models/skeleton.js', `export default '${JSON.stringify(root.toJSON())}';`) 17 | }); 18 | 19 | -------------------------------------------------------------------------------- /html/src/cothority-protobuf.js: -------------------------------------------------------------------------------- 1 | 2 | import Root from './models/root' 3 | 4 | /** 5 | * Base class for the protobuf library that provides helpers to encode and decode 6 | * messages according to a given model 7 | * 8 | * @author Gaylor Bosson (gaylor.bosson@epfl.ch) 9 | */ 10 | export default class CothorityProtobuf { 11 | 12 | /** 13 | * @constructor 14 | */ 15 | constructor() { 16 | this.root = Root; 17 | } 18 | 19 | /** 20 | * Encode a model to be transmitted over websocket 21 | * @param {String} name 22 | * @param {Object} fields 23 | * @returns {*|Buffer|Uint8Array} 24 | */ 25 | encodeMessage(name, fields) { 26 | const model = this.getModel(name); 27 | 28 | // Create the message with the model 29 | const msg = model.create(fields); 30 | 31 | // Encode the message in a BufferArray 32 | return model.encode(msg).finish(); 33 | } 34 | 35 | /** 36 | * Decode a message coming from a websocket 37 | * @param {String} name 38 | * @param {*|Buffer|Uint8Array} buffer 39 | */ 40 | decodeMessage(name, buffer) { 41 | const model = this.getModel(name); 42 | return model.decode(buffer); 43 | } 44 | 45 | /** 46 | * Return the protobuf loaded model 47 | * @param {String} name 48 | * @returns {ReflectionObject|?ReflectionObject|string} 49 | */ 50 | getModel(name) { 51 | return this.root.lookup(`${name}`); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /html/src/cothority-protobuf.test.js: -------------------------------------------------------------------------------- 1 | import CP from './cothority-protobuf' 2 | import Faker from 'faker' 3 | import ByteBuffer from 'bytebuffer' 4 | 5 | const CothorityProtobuf = new CP(); 6 | 7 | const mockSignReq = "CiCAHxMpFWVDC2nQwYfKiXWtrOGwZRS0Aw9T/ZOkwK3ZwxJgEl4KIOXiPlhTmgnTIR2PoPs0ddSGVeDAbYPpPI5uf" + 8 | "Raqh8EGEhCyCNMGs0dR/Luz1OnIZYjZGhd0Y3A6Ly83OC40Ni4yMjcuNjA6Nzc3MCIPSW5laXRpJ3Mgc2VydmVy"; 9 | 10 | describe('Protobuf', () => { 11 | 12 | it('should encode and decode correctly', () => { 13 | const encoded = CothorityProtobuf.encodeMessage('StatusResponse', { 14 | system: { 15 | status1: { 16 | field: { 17 | field1: 'success' 18 | } 19 | } 20 | }, 21 | server: { 22 | address: Faker.internet.ip(), 23 | description: Faker.lorem.sentence(), 24 | public: Uint8Array.from([1, 1, 1, 1]), 25 | id: Uint8Array.from([2, 2, 2, 2]) 26 | } 27 | }); 28 | 29 | const decoded = CothorityProtobuf.decodeMessage('StatusResponse', encoded); 30 | 31 | expect(decoded.server.public).toBeDefined(); 32 | expect(decoded.system.status1.field.field1).toBe('success'); 33 | }); 34 | 35 | it('should decode and encode in the same way', () => { 36 | const buffer = Uint8Array.from(atob(mockSignReq), c => c.charCodeAt(0)); 37 | 38 | const decoded = CothorityProtobuf.decodeMessage('SignatureRequest', buffer); 39 | const encoded = CothorityProtobuf.encodeMessage('SignatureRequest', decoded); 40 | 41 | expect(ByteBuffer.wrap(encoded).toBase64()).toBe(mockSignReq); 42 | }); 43 | 44 | }); 45 | -------------------------------------------------------------------------------- /html/src/models/cothority_template.proto: -------------------------------------------------------------------------------- 1 | message ClockRequest { 2 | required Roster Roster = 1; 3 | } 4 | 5 | message ClockResponse { 6 | required double Time = 1; 7 | required sint32 Children = 2; 8 | } 9 | 10 | message CountRequest { 11 | } 12 | 13 | message CountResponse { 14 | required sint32 Count = 1; 15 | } -------------------------------------------------------------------------------- /html/src/models/root.js: -------------------------------------------------------------------------------- 1 | import protobuf from "protobufjs" 2 | import skeleton from './skeleton' 3 | 4 | const {Root} = protobuf; 5 | 6 | /** 7 | * As we need to create a bundle, we cannot use the *.proto files and the a script will wrap 8 | * them in a skeleton file that contains the JSON representation that can be used in the js code 9 | */ 10 | export default Root.fromJSON(JSON.parse(skeleton)); -------------------------------------------------------------------------------- /html/src/models/roster.proto: -------------------------------------------------------------------------------- 1 | 2 | message Roster { 3 | optional bytes Id = 1; 4 | repeated ServerIdentity List = 2; 5 | optional bytes Aggregate = 3; 6 | } 7 | -------------------------------------------------------------------------------- /html/src/models/server-identity.proto: -------------------------------------------------------------------------------- 1 | message ServerIdentity{ 2 | optional bytes Public = 1; 3 | optional bytes Id = 2; 4 | required string Address = 3; 5 | optional string Description = 4; 6 | } -------------------------------------------------------------------------------- /html/src/models/skeleton.js: -------------------------------------------------------------------------------- 1 | export default '{"nested":{"cothority":{},"ClockRequest":{"fields":{"Roster":{"rule":"required","type":"Roster","id":1}}},"ClockResponse":{"fields":{"Time":{"rule":"required","type":"double","id":1},"Children":{"rule":"required","type":"sint32","id":2}}},"CountRequest":{"fields":{}},"CountResponse":{"fields":{"Count":{"rule":"required","type":"sint32","id":1}}},"Roster":{"fields":{"Id":{"type":"bytes","id":1},"List":{"rule":"repeated","type":"ServerIdentity","id":2,"options":{"packed":false}},"Aggregate":{"type":"bytes","id":3}}},"ServerIdentity":{"fields":{"Public":{"type":"bytes","id":1},"Id":{"type":"bytes","id":2},"Address":{"rule":"required","type":"string","id":3},"Description":{"type":"string","id":4}}},"StatusRequest":{"fields":{}},"StatusResponse":{"fields":{"system":{"keyType":"string","type":"Status","id":1},"server":{"type":"ServerIdentity","id":2}},"nested":{"Status":{"fields":{"field":{"keyType":"string","type":"string","id":1}}}}}}}'; -------------------------------------------------------------------------------- /html/src/models/status.proto: -------------------------------------------------------------------------------- 1 | message StatusRequest{ 2 | 3 | } 4 | 5 | message StatusResponse { 6 | map system = 1; 7 | optional ServerIdentity server = 2; 8 | 9 | message Status { 10 | map field = 1; 11 | } 12 | } -------------------------------------------------------------------------------- /html/src/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cothority-protobuf", 3 | "version": "0.0.1", 4 | "description": "Cothority messages over protobuf", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "jest" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/Gilthoniel/CothorityProtoBuf.git" 12 | }, 13 | "keywords": [ 14 | "cothority", 15 | "protobuf" 16 | ], 17 | "author": "Gaylor Bosson", 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/Gilthoniel/CothorityProtoBuf/issues" 21 | }, 22 | "homepage": "https://github.com/Gilthoniel/CothorityProtoBuf#readme", 23 | "dependencies": { 24 | "bytebuffer": "^5.0.1", 25 | "protobufjs": "^6.6.3" 26 | }, 27 | "devDependencies": { 28 | "babel-jest": "^19.0.0", 29 | "babel-preset-es2015": "^6.22.0", 30 | "babel-preset-es2015-rollup": "^3.0.0", 31 | "faker": "^4.1.0", 32 | "jest": "^19.0.2", 33 | "rollup": "^0.41.6", 34 | "rollup-plugin-babel": "^2.7.1", 35 | "watchify": "^3.9.0" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /log/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | Contributors to log15: 2 | 3 | - Aaron L 4 | - Alan Shreve 5 | - Chris Hines 6 | - Ciaran Downey 7 | - Dmitry Chestnykh 8 | - Evan Shaw 9 | - Péter Szilágyi 10 | - Trevor Gattis 11 | - Vincent Vanackere 12 | -------------------------------------------------------------------------------- /log/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2014 Alan Shreve 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /log/README_ETHEREUM.md: -------------------------------------------------------------------------------- 1 | This package is a fork of https://github.com/inconshreveable/log15, with some 2 | minor modifications required by the go-ethereum codebase: 3 | 4 | * Support for log level `trace` 5 | * Modified behavior to exit on `critical` failure 6 | -------------------------------------------------------------------------------- /log/handler_go13.go: -------------------------------------------------------------------------------- 1 | // +build !go1.4 2 | 3 | package log 4 | 5 | import ( 6 | "sync/atomic" 7 | "unsafe" 8 | ) 9 | 10 | // swapHandler wraps another handler that may be swapped out 11 | // dynamically at runtime in a thread-safe fashion. 12 | type swapHandler struct { 13 | handler unsafe.Pointer 14 | } 15 | 16 | func (h *swapHandler) Log(r *Record) error { 17 | return h.Get().Log(r) 18 | } 19 | 20 | func (h *swapHandler) Get() Handler { 21 | return *(*Handler)(atomic.LoadPointer(&h.handler)) 22 | } 23 | 24 | func (h *swapHandler) Swap(newHandler Handler) { 25 | atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) 26 | } 27 | -------------------------------------------------------------------------------- /log/handler_go14.go: -------------------------------------------------------------------------------- 1 | // +build go1.4 2 | 3 | package log 4 | 5 | import "sync/atomic" 6 | 7 | // swapHandler wraps another handler that may be swapped out 8 | // dynamically at runtime in a thread-safe fashion. 9 | type swapHandler struct { 10 | handler atomic.Value 11 | } 12 | 13 | func (h *swapHandler) Log(r *Record) error { 14 | return (*h.handler.Load().(*Handler)).Log(r) 15 | } 16 | 17 | func (h *swapHandler) Swap(newHandler Handler) { 18 | h.handler.Store(&newHandler) 19 | } 20 | 21 | func (h *swapHandler) Get() Handler { 22 | return *h.handler.Load().(*Handler) 23 | } 24 | -------------------------------------------------------------------------------- /log/root.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "os" 5 | ) 6 | 7 | var ( 8 | root = &logger{[]interface{}{}, new(swapHandler)} 9 | StdoutHandler = StreamHandler(os.Stdout, LogfmtFormat()) 10 | StderrHandler = StreamHandler(os.Stderr, LogfmtFormat()) 11 | ) 12 | 13 | func init() { 14 | root.SetHandler(DiscardHandler()) 15 | } 16 | 17 | // New returns a new logger with the given context. 18 | // New is a convenient alias for Root().New 19 | func New(ctx ...interface{}) Logger { 20 | return root.New(ctx...) 21 | } 22 | 23 | // Root returns the root logger 24 | func Root() Logger { 25 | return root 26 | } 27 | 28 | // The following functions bypass the exported logger methods (logger.Debug, 29 | // etc.) to keep the call depth the same for all paths to logger.write so 30 | // runtime.Caller(2) always refers to the call site in client code. 31 | 32 | // Trace is a convenient alias for Root().Trace 33 | func Trace(msg string, ctx ...interface{}) { 34 | root.write(msg, LvlTrace, ctx) 35 | } 36 | 37 | // Debug is a convenient alias for Root().Debug 38 | func Debug(msg string, ctx ...interface{}) { 39 | root.write(msg, LvlDebug, ctx) 40 | } 41 | 42 | // Info is a convenient alias for Root().Info 43 | func Info(msg string, ctx ...interface{}) { 44 | root.write(msg, LvlInfo, ctx) 45 | } 46 | 47 | // Warn is a convenient alias for Root().Warn 48 | func Warn(msg string, ctx ...interface{}) { 49 | root.write(msg, LvlWarn, ctx) 50 | } 51 | 52 | // Error is a convenient alias for Root().Error 53 | func Error(msg string, ctx ...interface{}) { 54 | root.write(msg, LvlError, ctx) 55 | } 56 | 57 | // Crit is a convenient alias for Root().Crit 58 | func Crit(msg string, ctx ...interface{}) { 59 | root.write(msg, LvlCrit, ctx) 60 | os.Exit(1) 61 | } 62 | -------------------------------------------------------------------------------- /log/syslog.go: -------------------------------------------------------------------------------- 1 | // +build !windows,!plan9 2 | 3 | package log 4 | 5 | import ( 6 | "log/syslog" 7 | "strings" 8 | ) 9 | 10 | // SyslogHandler opens a connection to the system syslog daemon by calling 11 | // syslog.New and writes all records to it. 12 | func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error) { 13 | wr, err := syslog.New(priority, tag) 14 | return sharedSyslog(fmtr, wr, err) 15 | } 16 | 17 | // SyslogNetHandler opens a connection to a log daemon over the network and writes 18 | // all log records to it. 19 | func SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) (Handler, error) { 20 | wr, err := syslog.Dial(net, addr, priority, tag) 21 | return sharedSyslog(fmtr, wr, err) 22 | } 23 | 24 | func sharedSyslog(fmtr Format, sysWr *syslog.Writer, err error) (Handler, error) { 25 | if err != nil { 26 | return nil, err 27 | } 28 | h := FuncHandler(func(r *Record) error { 29 | var syslogFn = sysWr.Info 30 | switch r.Lvl { 31 | case LvlCrit: 32 | syslogFn = sysWr.Crit 33 | case LvlError: 34 | syslogFn = sysWr.Err 35 | case LvlWarn: 36 | syslogFn = sysWr.Warning 37 | case LvlInfo: 38 | syslogFn = sysWr.Info 39 | case LvlDebug: 40 | syslogFn = sysWr.Debug 41 | case LvlTrace: 42 | syslogFn = func(m string) error { return nil } // There's no syslog level for trace 43 | } 44 | 45 | s := strings.TrimSpace(string(fmtr.Format(r))) 46 | return syslogFn(s) 47 | }) 48 | return LazyHandler(&closingHandler{sysWr, h}), nil 49 | } 50 | 51 | func (m muster) SyslogHandler(priority syslog.Priority, tag string, fmtr Format) Handler { 52 | return must(SyslogHandler(priority, tag, fmtr)) 53 | } 54 | 55 | func (m muster) SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) Handler { 56 | return must(SyslogNetHandler(net, addr, priority, tag, fmtr)) 57 | } 58 | -------------------------------------------------------------------------------- /log/term/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Simon Eskildsen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /log/term/terminal_appengine.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build appengine 7 | 8 | package term 9 | 10 | // IsTty always returns false on AppEngine. 11 | func IsTty(fd uintptr) bool { 12 | return false 13 | } 14 | -------------------------------------------------------------------------------- /log/term/terminal_darwin.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | // +build !appengine 6 | 7 | package term 8 | 9 | import "syscall" 10 | 11 | const ioctlReadTermios = syscall.TIOCGETA 12 | 13 | type Termios syscall.Termios 14 | -------------------------------------------------------------------------------- /log/term/terminal_freebsd.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import ( 4 | "syscall" 5 | ) 6 | 7 | const ioctlReadTermios = syscall.TIOCGETA 8 | 9 | // Go 1.2 doesn't include Termios for FreeBSD. This should be added in 1.3 and this could be merged with terminal_darwin. 10 | type Termios struct { 11 | Iflag uint32 12 | Oflag uint32 13 | Cflag uint32 14 | Lflag uint32 15 | Cc [20]uint8 16 | Ispeed uint32 17 | Ospeed uint32 18 | } 19 | -------------------------------------------------------------------------------- /log/term/terminal_linux.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build !appengine 7 | 8 | package term 9 | 10 | import "syscall" 11 | 12 | const ioctlReadTermios = syscall.TCGETS 13 | 14 | type Termios syscall.Termios 15 | -------------------------------------------------------------------------------- /log/term/terminal_netbsd.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import "syscall" 4 | 5 | const ioctlReadTermios = syscall.TIOCGETA 6 | 7 | type Termios syscall.Termios 8 | -------------------------------------------------------------------------------- /log/term/terminal_notwindows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build linux,!appengine darwin freebsd openbsd netbsd 7 | 8 | package term 9 | 10 | import ( 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | // IsTty returns true if the given file descriptor is a terminal. 16 | func IsTty(fd uintptr) bool { 17 | var termios Termios 18 | _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) 19 | return err == 0 20 | } 21 | -------------------------------------------------------------------------------- /log/term/terminal_openbsd.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import "syscall" 4 | 5 | const ioctlReadTermios = syscall.TIOCGETA 6 | 7 | type Termios syscall.Termios 8 | -------------------------------------------------------------------------------- /log/term/terminal_solaris.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import "golang.org/x/sys/unix" 4 | 5 | // IsTty returns true if the given file descriptor is a terminal. 6 | func IsTty(fd uintptr) bool { 7 | _, err := unix.IoctlGetTermios(int(fd), unix.TCGETA) 8 | return err == nil 9 | } 10 | -------------------------------------------------------------------------------- /log/term/terminal_windows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by a BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build windows 7 | 8 | package term 9 | 10 | import ( 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | var kernel32 = syscall.NewLazyDLL("kernel32.dll") 16 | 17 | var ( 18 | procGetConsoleMode = kernel32.NewProc("GetConsoleMode") 19 | ) 20 | 21 | // IsTty returns true if the given file descriptor is a terminal. 22 | func IsTty(fd uintptr) bool { 23 | var st uint32 24 | r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) 25 | return r != 0 && e == 0 26 | } 27 | -------------------------------------------------------------------------------- /metrics/FORK.md: -------------------------------------------------------------------------------- 1 | This repo has been forked from https://github.com/rcrowley/go-metrics at commit e181e09 2 | -------------------------------------------------------------------------------- /metrics/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2012 Richard Crowley. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | 1. Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above 11 | copyright notice, this list of conditions and the following 12 | disclaimer in the documentation and/or other materials provided 13 | with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY RICHARD CROWLEY ``AS IS'' AND ANY EXPRESS 16 | OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL RICHARD CROWLEY OR CONTRIBUTORS BE LIABLE 19 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 20 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 21 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 22 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 23 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 24 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 25 | THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | The views and conclusions contained in the software and documentation 28 | are those of the authors and should not be interpreted as representing 29 | official policies, either expressed or implied, of Richard Crowley. 30 | -------------------------------------------------------------------------------- /metrics/counter_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import "testing" 4 | 5 | func BenchmarkCounter(b *testing.B) { 6 | c := NewCounter() 7 | b.ResetTimer() 8 | for i := 0; i < b.N; i++ { 9 | c.Inc(1) 10 | } 11 | } 12 | 13 | func TestCounterClear(t *testing.T) { 14 | c := NewCounter() 15 | c.Inc(1) 16 | c.Clear() 17 | if count := c.Count(); 0 != count { 18 | t.Errorf("c.Count(): 0 != %v\n", count) 19 | } 20 | } 21 | 22 | func TestCounterDec1(t *testing.T) { 23 | c := NewCounter() 24 | c.Dec(1) 25 | if count := c.Count(); -1 != count { 26 | t.Errorf("c.Count(): -1 != %v\n", count) 27 | } 28 | } 29 | 30 | func TestCounterDec2(t *testing.T) { 31 | c := NewCounter() 32 | c.Dec(2) 33 | if count := c.Count(); -2 != count { 34 | t.Errorf("c.Count(): -2 != %v\n", count) 35 | } 36 | } 37 | 38 | func TestCounterInc1(t *testing.T) { 39 | c := NewCounter() 40 | c.Inc(1) 41 | if count := c.Count(); 1 != count { 42 | t.Errorf("c.Count(): 1 != %v\n", count) 43 | } 44 | } 45 | 46 | func TestCounterInc2(t *testing.T) { 47 | c := NewCounter() 48 | c.Inc(2) 49 | if count := c.Count(); 2 != count { 50 | t.Errorf("c.Count(): 2 != %v\n", count) 51 | } 52 | } 53 | 54 | func TestCounterSnapshot(t *testing.T) { 55 | c := NewCounter() 56 | c.Inc(1) 57 | snapshot := c.Snapshot() 58 | c.Inc(1) 59 | if count := snapshot.Count(); 1 != count { 60 | t.Errorf("c.Count(): 1 != %v\n", count) 61 | } 62 | } 63 | 64 | func TestCounterZero(t *testing.T) { 65 | c := NewCounter() 66 | if count := c.Count(); 0 != count { 67 | t.Errorf("c.Count(): 0 != %v\n", count) 68 | } 69 | } 70 | 71 | func TestGetOrRegisterCounter(t *testing.T) { 72 | r := NewRegistry() 73 | NewRegisteredCounter("foo", r).Inc(47) 74 | if c := GetOrRegisterCounter("foo", r); 47 != c.Count() { 75 | t.Fatal(c) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /metrics/debug_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "runtime" 5 | "runtime/debug" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func BenchmarkDebugGCStats(b *testing.B) { 11 | r := NewRegistry() 12 | RegisterDebugGCStats(r) 13 | b.ResetTimer() 14 | for i := 0; i < b.N; i++ { 15 | CaptureDebugGCStatsOnce(r) 16 | } 17 | } 18 | 19 | func TestDebugGCStatsBlocking(t *testing.T) { 20 | if g := runtime.GOMAXPROCS(0); g < 2 { 21 | t.Skipf("skipping TestDebugGCMemStatsBlocking with GOMAXPROCS=%d\n", g) 22 | return 23 | } 24 | ch := make(chan int) 25 | go testDebugGCStatsBlocking(ch) 26 | var gcStats debug.GCStats 27 | t0 := time.Now() 28 | debug.ReadGCStats(&gcStats) 29 | t1 := time.Now() 30 | t.Log("i++ during debug.ReadGCStats:", <-ch) 31 | go testDebugGCStatsBlocking(ch) 32 | d := t1.Sub(t0) 33 | t.Log(d) 34 | time.Sleep(d) 35 | t.Log("i++ during time.Sleep:", <-ch) 36 | } 37 | 38 | func testDebugGCStatsBlocking(ch chan int) { 39 | i := 0 40 | for { 41 | select { 42 | case ch <- i: 43 | return 44 | default: 45 | i++ 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /metrics/disk.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package metrics 18 | 19 | // DiskStats is the per process disk io stats. 20 | type DiskStats struct { 21 | ReadCount int64 // Number of read operations executed 22 | ReadBytes int64 // Total number of bytes read 23 | WriteCount int64 // Number of write operations executed 24 | WriteBytes int64 // Total number of byte written 25 | } 26 | -------------------------------------------------------------------------------- /metrics/disk_nop.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build !linux 18 | 19 | package metrics 20 | 21 | import "errors" 22 | 23 | // ReadDiskStats retrieves the disk IO stats belonging to the current process. 24 | func ReadDiskStats(stats *DiskStats) error { 25 | return errors.New("Not implemented") 26 | } 27 | -------------------------------------------------------------------------------- /metrics/gauge_float64_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import "testing" 4 | 5 | func BenchmarkGuageFloat64(b *testing.B) { 6 | g := NewGaugeFloat64() 7 | b.ResetTimer() 8 | for i := 0; i < b.N; i++ { 9 | g.Update(float64(i)) 10 | } 11 | } 12 | 13 | func TestGaugeFloat64(t *testing.T) { 14 | g := NewGaugeFloat64() 15 | g.Update(float64(47.0)) 16 | if v := g.Value(); float64(47.0) != v { 17 | t.Errorf("g.Value(): 47.0 != %v\n", v) 18 | } 19 | } 20 | 21 | func TestGaugeFloat64Snapshot(t *testing.T) { 22 | g := NewGaugeFloat64() 23 | g.Update(float64(47.0)) 24 | snapshot := g.Snapshot() 25 | g.Update(float64(0)) 26 | if v := snapshot.Value(); float64(47.0) != v { 27 | t.Errorf("g.Value(): 47.0 != %v\n", v) 28 | } 29 | } 30 | 31 | func TestGetOrRegisterGaugeFloat64(t *testing.T) { 32 | r := NewRegistry() 33 | NewRegisteredGaugeFloat64("foo", r).Update(float64(47.0)) 34 | t.Logf("registry: %v", r) 35 | if g := GetOrRegisterGaugeFloat64("foo", r); float64(47.0) != g.Value() { 36 | t.Fatal(g) 37 | } 38 | } 39 | 40 | func TestFunctionalGaugeFloat64(t *testing.T) { 41 | var counter float64 42 | fg := NewFunctionalGaugeFloat64(func() float64 { 43 | counter++ 44 | return counter 45 | }) 46 | fg.Value() 47 | fg.Value() 48 | if counter != 2 { 49 | t.Error("counter != 2") 50 | } 51 | } 52 | 53 | func TestGetOrRegisterFunctionalGaugeFloat64(t *testing.T) { 54 | r := NewRegistry() 55 | NewRegisteredFunctionalGaugeFloat64("foo", r, func() float64 { return 47 }) 56 | if g := GetOrRegisterGaugeFloat64("foo", r); 47 != g.Value() { 57 | t.Fatal(g) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /metrics/gauge_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func BenchmarkGuage(b *testing.B) { 9 | g := NewGauge() 10 | b.ResetTimer() 11 | for i := 0; i < b.N; i++ { 12 | g.Update(int64(i)) 13 | } 14 | } 15 | 16 | func TestGauge(t *testing.T) { 17 | g := NewGauge() 18 | g.Update(int64(47)) 19 | if v := g.Value(); 47 != v { 20 | t.Errorf("g.Value(): 47 != %v\n", v) 21 | } 22 | } 23 | 24 | func TestGaugeSnapshot(t *testing.T) { 25 | g := NewGauge() 26 | g.Update(int64(47)) 27 | snapshot := g.Snapshot() 28 | g.Update(int64(0)) 29 | if v := snapshot.Value(); 47 != v { 30 | t.Errorf("g.Value(): 47 != %v\n", v) 31 | } 32 | } 33 | 34 | func TestGetOrRegisterGauge(t *testing.T) { 35 | r := NewRegistry() 36 | NewRegisteredGauge("foo", r).Update(47) 37 | if g := GetOrRegisterGauge("foo", r); 47 != g.Value() { 38 | t.Fatal(g) 39 | } 40 | } 41 | 42 | func TestFunctionalGauge(t *testing.T) { 43 | var counter int64 44 | fg := NewFunctionalGauge(func() int64 { 45 | counter++ 46 | return counter 47 | }) 48 | fg.Value() 49 | fg.Value() 50 | if counter != 2 { 51 | t.Error("counter != 2") 52 | } 53 | } 54 | 55 | func TestGetOrRegisterFunctionalGauge(t *testing.T) { 56 | r := NewRegistry() 57 | NewRegisteredFunctionalGauge("foo", r, func() int64 { return 47 }) 58 | if g := GetOrRegisterGauge("foo", r); 47 != g.Value() { 59 | t.Fatal(g) 60 | } 61 | } 62 | 63 | func ExampleGetOrRegisterGauge() { 64 | m := "server.bytes_sent" 65 | g := GetOrRegisterGauge(m, nil) 66 | g.Update(47) 67 | fmt.Println(g.Value()) // Output: 47 68 | } 69 | -------------------------------------------------------------------------------- /metrics/graphite_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "net" 5 | "time" 6 | ) 7 | 8 | func ExampleGraphite() { 9 | addr, _ := net.ResolveTCPAddr("net", ":2003") 10 | go Graphite(DefaultRegistry, 1*time.Second, "some.prefix", addr) 11 | } 12 | 13 | func ExampleGraphiteWithConfig() { 14 | addr, _ := net.ResolveTCPAddr("net", ":2003") 15 | go GraphiteWithConfig(GraphiteConfig{ 16 | Addr: addr, 17 | Registry: DefaultRegistry, 18 | FlushInterval: 1 * time.Second, 19 | DurationUnit: time.Millisecond, 20 | Percentiles: []float64{0.5, 0.75, 0.99, 0.999}, 21 | }) 22 | } 23 | -------------------------------------------------------------------------------- /metrics/healthcheck.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | // Healthchecks hold an error value describing an arbitrary up/down status. 4 | type Healthcheck interface { 5 | Check() 6 | Error() error 7 | Healthy() 8 | Unhealthy(error) 9 | } 10 | 11 | // NewHealthcheck constructs a new Healthcheck which will use the given 12 | // function to update its status. 13 | func NewHealthcheck(f func(Healthcheck)) Healthcheck { 14 | if !Enabled { 15 | return NilHealthcheck{} 16 | } 17 | return &StandardHealthcheck{nil, f} 18 | } 19 | 20 | // NilHealthcheck is a no-op. 21 | type NilHealthcheck struct{} 22 | 23 | // Check is a no-op. 24 | func (NilHealthcheck) Check() {} 25 | 26 | // Error is a no-op. 27 | func (NilHealthcheck) Error() error { return nil } 28 | 29 | // Healthy is a no-op. 30 | func (NilHealthcheck) Healthy() {} 31 | 32 | // Unhealthy is a no-op. 33 | func (NilHealthcheck) Unhealthy(error) {} 34 | 35 | // StandardHealthcheck is the standard implementation of a Healthcheck and 36 | // stores the status and a function to call to update the status. 37 | type StandardHealthcheck struct { 38 | err error 39 | f func(Healthcheck) 40 | } 41 | 42 | // Check runs the healthcheck function to update the healthcheck's status. 43 | func (h *StandardHealthcheck) Check() { 44 | h.f(h) 45 | } 46 | 47 | // Error returns the healthcheck's status, which will be nil if it is healthy. 48 | func (h *StandardHealthcheck) Error() error { 49 | return h.err 50 | } 51 | 52 | // Healthy marks the healthcheck as healthy. 53 | func (h *StandardHealthcheck) Healthy() { 54 | h.err = nil 55 | } 56 | 57 | // Unhealthy marks the healthcheck as unhealthy. The error is stored and 58 | // may be retrieved by the Error method. 59 | func (h *StandardHealthcheck) Unhealthy(err error) { 60 | h.err = err 61 | } 62 | -------------------------------------------------------------------------------- /metrics/influxdb/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Vincent Rischmann 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /metrics/influxdb/README.md: -------------------------------------------------------------------------------- 1 | go-metrics-influxdb 2 | =================== 3 | 4 | This is a reporter for the [go-metrics](https://github.com/rcrowley/go-metrics) library which will post the metrics to [InfluxDB](https://influxdb.com/). 5 | 6 | Note 7 | ---- 8 | 9 | This is only compatible with InfluxDB 0.9+. 10 | 11 | Usage 12 | ----- 13 | 14 | ```go 15 | import "github.com/vrischmann/go-metrics-influxdb" 16 | 17 | go influxdb.InfluxDB( 18 | metrics.DefaultRegistry, // metrics registry 19 | time.Second * 10, // interval 20 | "http://localhost:8086", // the InfluxDB url 21 | "mydb", // your InfluxDB database 22 | "myuser", // your InfluxDB user 23 | "mypassword", // your InfluxDB password 24 | ) 25 | ``` 26 | 27 | License 28 | ------- 29 | 30 | go-metrics-influxdb is licensed under the MIT license. See the LICENSE file for details. 31 | -------------------------------------------------------------------------------- /metrics/init_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | func init() { 4 | Enabled = true 5 | } 6 | -------------------------------------------------------------------------------- /metrics/json.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "encoding/json" 5 | "io" 6 | "time" 7 | ) 8 | 9 | // MarshalJSON returns a byte slice containing a JSON representation of all 10 | // the metrics in the Registry. 11 | func (r *StandardRegistry) MarshalJSON() ([]byte, error) { 12 | return json.Marshal(r.GetAll()) 13 | } 14 | 15 | // WriteJSON writes metrics from the given registry periodically to the 16 | // specified io.Writer as JSON. 17 | func WriteJSON(r Registry, d time.Duration, w io.Writer) { 18 | for range time.Tick(d) { 19 | WriteJSONOnce(r, w) 20 | } 21 | } 22 | 23 | // WriteJSONOnce writes metrics from the given registry to the specified 24 | // io.Writer as JSON. 25 | func WriteJSONOnce(r Registry, w io.Writer) { 26 | json.NewEncoder(w).Encode(r) 27 | } 28 | 29 | func (p *PrefixedRegistry) MarshalJSON() ([]byte, error) { 30 | return json.Marshal(p.GetAll()) 31 | } 32 | -------------------------------------------------------------------------------- /metrics/json_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "testing" 7 | ) 8 | 9 | func TestRegistryMarshallJSON(t *testing.T) { 10 | b := &bytes.Buffer{} 11 | enc := json.NewEncoder(b) 12 | r := NewRegistry() 13 | r.Register("counter", NewCounter()) 14 | enc.Encode(r) 15 | if s := b.String(); "{\"counter\":{\"count\":0}}\n" != s { 16 | t.Fatalf(s) 17 | } 18 | } 19 | 20 | func TestRegistryWriteJSONOnce(t *testing.T) { 21 | r := NewRegistry() 22 | r.Register("counter", NewCounter()) 23 | b := &bytes.Buffer{} 24 | WriteJSONOnce(r, b) 25 | if s := b.String(); s != "{\"counter\":{\"count\":0}}\n" { 26 | t.Fail() 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /metrics/meter_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | ) 7 | 8 | func BenchmarkMeter(b *testing.B) { 9 | m := NewMeter() 10 | b.ResetTimer() 11 | for i := 0; i < b.N; i++ { 12 | m.Mark(1) 13 | } 14 | } 15 | 16 | func TestGetOrRegisterMeter(t *testing.T) { 17 | r := NewRegistry() 18 | NewRegisteredMeter("foo", r).Mark(47) 19 | if m := GetOrRegisterMeter("foo", r); 47 != m.Count() { 20 | t.Fatal(m) 21 | } 22 | } 23 | 24 | func TestMeterDecay(t *testing.T) { 25 | ma := meterArbiter{ 26 | ticker: time.NewTicker(time.Millisecond), 27 | meters: make(map[*StandardMeter]struct{}), 28 | } 29 | m := newStandardMeter() 30 | ma.meters[m] = struct{}{} 31 | go ma.tick() 32 | m.Mark(1) 33 | rateMean := m.RateMean() 34 | time.Sleep(100 * time.Millisecond) 35 | if m.RateMean() >= rateMean { 36 | t.Error("m.RateMean() didn't decrease") 37 | } 38 | } 39 | 40 | func TestMeterNonzero(t *testing.T) { 41 | m := NewMeter() 42 | m.Mark(3) 43 | if count := m.Count(); 3 != count { 44 | t.Errorf("m.Count(): 3 != %v\n", count) 45 | } 46 | } 47 | 48 | func TestMeterStop(t *testing.T) { 49 | l := len(arbiter.meters) 50 | m := NewMeter() 51 | if len(arbiter.meters) != l+1 { 52 | t.Errorf("arbiter.meters: %d != %d\n", l+1, len(arbiter.meters)) 53 | } 54 | m.Stop() 55 | if len(arbiter.meters) != l { 56 | t.Errorf("arbiter.meters: %d != %d\n", l, len(arbiter.meters)) 57 | } 58 | } 59 | 60 | func TestMeterSnapshot(t *testing.T) { 61 | m := NewMeter() 62 | m.Mark(1) 63 | if snapshot := m.Snapshot(); m.RateMean() != snapshot.RateMean() { 64 | t.Fatal(snapshot) 65 | } 66 | } 67 | 68 | func TestMeterZero(t *testing.T) { 69 | m := NewMeter() 70 | if count := m.Count(); 0 != count { 71 | t.Errorf("m.Count(): 0 != %v\n", count) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /metrics/opentsdb_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "net" 5 | "time" 6 | ) 7 | 8 | func ExampleOpenTSDB() { 9 | addr, _ := net.ResolveTCPAddr("net", ":2003") 10 | go OpenTSDB(DefaultRegistry, 1*time.Second, "some.prefix", addr) 11 | } 12 | 13 | func ExampleOpenTSDBWithConfig() { 14 | addr, _ := net.ResolveTCPAddr("net", ":2003") 15 | go OpenTSDBWithConfig(OpenTSDBConfig{ 16 | Addr: addr, 17 | Registry: DefaultRegistry, 18 | FlushInterval: 1 * time.Second, 19 | DurationUnit: time.Millisecond, 20 | }) 21 | } 22 | -------------------------------------------------------------------------------- /metrics/runtime_cgo.go: -------------------------------------------------------------------------------- 1 | // +build cgo 2 | // +build !appengine 3 | 4 | package metrics 5 | 6 | import "runtime" 7 | 8 | func numCgoCall() int64 { 9 | return runtime.NumCgoCall() 10 | } 11 | -------------------------------------------------------------------------------- /metrics/runtime_gccpufraction.go: -------------------------------------------------------------------------------- 1 | // +build go1.5 2 | 3 | package metrics 4 | 5 | import "runtime" 6 | 7 | func gcCPUFraction(memStats *runtime.MemStats) float64 { 8 | return memStats.GCCPUFraction 9 | } 10 | -------------------------------------------------------------------------------- /metrics/runtime_no_cgo.go: -------------------------------------------------------------------------------- 1 | // +build !cgo appengine 2 | 3 | package metrics 4 | 5 | func numCgoCall() int64 { 6 | return 0 7 | } 8 | -------------------------------------------------------------------------------- /metrics/runtime_no_gccpufraction.go: -------------------------------------------------------------------------------- 1 | // +build !go1.5 2 | 3 | package metrics 4 | 5 | import "runtime" 6 | 7 | func gcCPUFraction(memStats *runtime.MemStats) float64 { 8 | return 0 9 | } 10 | -------------------------------------------------------------------------------- /metrics/validate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | # check there are no formatting issues 6 | GOFMT_LINES=`gofmt -l . | wc -l | xargs` 7 | test $GOFMT_LINES -eq 0 || echo "gofmt needs to be run, ${GOFMT_LINES} files have issues" 8 | 9 | # run the tests for the root package 10 | go test -race . 11 | -------------------------------------------------------------------------------- /metrics/writer_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "sort" 5 | "testing" 6 | ) 7 | 8 | func TestMetricsSorting(t *testing.T) { 9 | var namedMetrics = namedMetricSlice{ 10 | {name: "zzz"}, 11 | {name: "bbb"}, 12 | {name: "fff"}, 13 | {name: "ggg"}, 14 | } 15 | 16 | sort.Sort(namedMetrics) 17 | for i, name := range []string{"bbb", "fff", "ggg", "zzz"} { 18 | if namedMetrics[i].name != name { 19 | t.Fail() 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /params/denomination.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package params 18 | 19 | const ( 20 | // These are the multipliers for ether denominations. 21 | // Example: To get the wei value of an amount in 'douglas', use 22 | // 23 | // new(big.Int).Mul(value, big.NewInt(params.Douglas)) 24 | // 25 | Wei = 1 26 | Ada = 1e3 27 | Babbage = 1e6 28 | Shannon = 1e9 29 | Szabo = 1e12 30 | Finney = 1e15 31 | Ether = 1e18 32 | Einstein = 1e21 33 | Douglas = 1e42 34 | ) 35 | -------------------------------------------------------------------------------- /params/network_params.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package params 18 | 19 | // These are network parameters that need to be constant between clients, but 20 | // aren't necesarilly consensus related. 21 | 22 | const ( 23 | // BloomBitsBlocks is the number of blocks a single bloom bit section vector 24 | // contains. 25 | BloomBitsBlocks uint64 = 4096 26 | ) 27 | -------------------------------------------------------------------------------- /params/version.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package params 18 | 19 | import ( 20 | "fmt" 21 | ) 22 | 23 | const ( 24 | VersionMajor = 1 // Major version component of the current release 25 | VersionMinor = 8 // Minor version component of the current release 26 | VersionPatch = 5 // Patch version component of the current release 27 | VersionMeta = "unstable" // Version metadata to append to the version string 28 | ) 29 | 30 | // Version holds the textual version string. 31 | var Version = func() string { 32 | v := fmt.Sprintf("%d.%d.%d", VersionMajor, VersionMinor, VersionPatch) 33 | if VersionMeta != "" { 34 | v += "-" + VersionMeta 35 | } 36 | return v 37 | }() 38 | 39 | func VersionWithCommit(gitCommit string) string { 40 | vsn := Version 41 | if len(gitCommit) >= 8 { 42 | vsn += "-" + gitCommit[:8] 43 | } 44 | return vsn 45 | } 46 | -------------------------------------------------------------------------------- /protobuf/lib.go: -------------------------------------------------------------------------------- 1 | package stream 2 | 3 | import ( 4 | "encoding/binary" 5 | "io" 6 | "sync" 7 | 8 | "github.com/gogo/protobuf/proto" 9 | ) 10 | 11 | type Message interface { 12 | proto.Marshaler 13 | proto.Unmarshaler 14 | proto.Sizer 15 | } 16 | 17 | type LockableWriter interface { 18 | sync.Locker 19 | io.Writer 20 | } 21 | 22 | const bytesForSize = 8 23 | 24 | // Write writes the marshalled message into the writer 25 | func Write(w io.Writer, m Message) (err error) { 26 | messageBytes, err := m.Marshal() 27 | 28 | if err == nil { 29 | size := m.Size() 30 | sizeBytes := make([]byte, bytesForSize) 31 | binary.BigEndian.PutUint64(sizeBytes, uint64(size)) 32 | 33 | w.Write(sizeBytes) 34 | w.Write(messageBytes) 35 | } 36 | 37 | return 38 | } 39 | 40 | // WriteWithLock is just like Write, but will lock on write 41 | func WriteWithLock(w LockableWriter, m Message) (err error) { 42 | messageBytes, err := m.Marshal() 43 | 44 | if err == nil { 45 | size := m.Size() 46 | sizeBytes := make([]byte, bytesForSize) 47 | binary.BigEndian.PutUint64(sizeBytes, uint64(size)) 48 | 49 | w.Lock() 50 | defer w.Unlock() 51 | w.Write(sizeBytes) 52 | w.Write(messageBytes) 53 | } 54 | 55 | return 56 | } 57 | 58 | // Read reads the message from the reader 59 | func Read(r io.Reader, m Message) (err error) { 60 | sizeBytes := make([]byte, bytesForSize) 61 | 62 | if _, err = io.ReadFull(r, sizeBytes); err == nil { 63 | size := binary.BigEndian.Uint64(sizeBytes) 64 | messageBytes := make([]byte, size) 65 | 66 | if _, err = io.ReadFull(r, messageBytes); err == nil { 67 | m.Unmarshal(messageBytes) 68 | } 69 | } 70 | 71 | return 72 | } 73 | -------------------------------------------------------------------------------- /protobuf/lib.proto: -------------------------------------------------------------------------------- 1 | syntax="proto3"; 2 | package stream; 3 | 4 | message TransactionMock { 5 | uint32 Version = 1; 6 | bytes SenderKey = 3; 7 | bytes Recipient = 4; 8 | bytes Quantity = 5; 9 | bytes Data = 6; 10 | uint64 AvailGas = 7; 11 | bytes GasPrice = 8; 12 | } -------------------------------------------------------------------------------- /protocol/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package protocol contains an example demonstrating how to write a 3 | protocol and a simulation. 4 | 5 | The protocol has two messages: 6 | - Announce which is sent from the root down the tree 7 | - Reply which is sent back up to the root 8 | 9 | If you want to add other messages, be sure to follow the way Announce and 10 | StructAnnounce are set up. 11 | 12 | A simple protocol uses four files: 13 | - struct.go defines the messages sent around 14 | - protocol.go defines the actions for each message 15 | - protocol_test.go tests the protocol in a local test 16 | - simulation.go tests the protocol on distant platforms like deterlab 17 | */ 18 | package protocol 19 | -------------------------------------------------------------------------------- /protocol/protocol_test.go: -------------------------------------------------------------------------------- 1 | package protocol_test 2 | 3 | /* 4 | The test-file should at the very least run the protocol for a varying number 5 | of nodes. It is even better practice to test the different methods of the 6 | protocol, as in Test Driven Development. 7 | */ 8 | 9 | import ( 10 | "testing" 11 | "time" 12 | 13 | "github.com/cypherium_private/mvp/protocol" 14 | "github.com/dedis/kyber/suites" 15 | "github.com/dedis/onet" 16 | "github.com/dedis/onet/log" 17 | "github.com/dedis/onet/network" 18 | "github.com/stretchr/testify/require" 19 | ) 20 | 21 | var tSuite = suites.MustFind("Ed25519") 22 | 23 | func TestMain(m *testing.M) { 24 | log.MainTest(m) 25 | } 26 | 27 | // Tests a 2, 5 and 13-node system. It is good practice to test different 28 | // sizes of trees to make sure your protocol is stable. 29 | func TestNode(t *testing.T) { 30 | log.SetDebugVisible(5) 31 | nodes := []int{15} 32 | for _, nbrNodes := range nodes { 33 | local := onet.NewLocalTest(tSuite) 34 | _, _, tree := local.GenTree(nbrNodes, true) 35 | log.Lvl3(tree.Dump()) 36 | 37 | pi, err := local.StartProtocol("Template", tree) 38 | require.Nil(t, err) 39 | protocol := pi.(*protocol.TemplateProtocol) 40 | timeout := network.WaitRetry * time.Duration(network.MaxRetryConnect*nbrNodes*2) * time.Millisecond 41 | select { 42 | case children := <-protocol.ChildCount: 43 | log.Lvl2("Instance 1 is done") 44 | require.Equal(t, children, nbrNodes, "Didn't get a child-cound of", nbrNodes) 45 | case <-time.After(timeout): 46 | t.Fatal("Didn't finish in time") 47 | } 48 | local.CloseAll() 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /protocol/struct.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | /* 4 | Struct holds the messages that will be sent around in the protocol. You have 5 | to define each message twice: once the actual message, and a second time 6 | with the `*onet.TreeNode` embedded. The latter is used in the handler-function 7 | so that it can find out who sent the message. 8 | */ 9 | 10 | import "github.com/dedis/onet" 11 | 12 | // Name can be used from other packages to refer to this protocol. 13 | const Name = "Template" 14 | 15 | // Announce is used to pass a message to all children. 16 | type Announce struct { 17 | Message string 18 | } 19 | 20 | // StructAnnounce just contains Announce and the data necessary to identify and 21 | // process the message in the sda framework. 22 | type StructAnnounce struct { 23 | *onet.TreeNode 24 | Announce 25 | } 26 | 27 | // Reply returns the count of all children. 28 | type Reply struct { 29 | ChildrenCount int 30 | } 31 | 32 | // StructReply just contains Reply and the data necessary to identify and 33 | // process the message in the sda framework. 34 | type StructReply struct { 35 | *onet.TreeNode 36 | Reply 37 | } 38 | -------------------------------------------------------------------------------- /rlp/decode_tail_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package rlp 18 | 19 | import ( 20 | "bytes" 21 | "fmt" 22 | ) 23 | 24 | type structWithTail struct { 25 | A, B uint 26 | C []uint `rlp:"tail"` 27 | } 28 | 29 | func ExampleDecode_structTagTail() { 30 | // In this example, the "tail" struct tag is used to decode lists of 31 | // differing length into a struct. 32 | var val structWithTail 33 | 34 | err := Decode(bytes.NewReader([]byte{0xC4, 0x01, 0x02, 0x03, 0x04}), &val) 35 | fmt.Printf("with 4 elements: err=%v val=%v\n", err, val) 36 | 37 | err = Decode(bytes.NewReader([]byte{0xC6, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), &val) 38 | fmt.Printf("with 6 elements: err=%v val=%v\n", err, val) 39 | 40 | // Note that at least two list elements must be present to 41 | // fill fields A and B: 42 | err = Decode(bytes.NewReader([]byte{0xC1, 0x01}), &val) 43 | fmt.Printf("with 1 element: err=%q\n", err) 44 | 45 | // Output: 46 | // with 4 elements: err= val={1 2 [3 4]} 47 | // with 6 elements: err= val={1 2 [3 4 5 6]} 48 | // with 1 element: err="rlp: too few elements for rlp.structWithTail" 49 | } 50 | -------------------------------------------------------------------------------- /rlp/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | /* 18 | Package rlp implements the RLP serialization format. 19 | 20 | The purpose of RLP (Recursive Linear Prefix) is to encode arbitrarily 21 | nested arrays of binary data, and RLP is the main encoding method used 22 | to serialize objects in Ethereum. The only purpose of RLP is to encode 23 | structure; encoding specific atomic data types (eg. strings, ints, 24 | floats) is left up to higher-order protocols; in Ethereum integers 25 | must be represented in big endian binary form with no leading zeroes 26 | (thus making the integer value zero equivalent to the empty byte 27 | array). 28 | 29 | RLP values are distinguished by a type tag. The type tag precedes the 30 | value in the input stream and defines the size and kind of the bytes 31 | that follow. 32 | */ 33 | package rlp 34 | -------------------------------------------------------------------------------- /rlp/encoder_example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package rlp 18 | 19 | import ( 20 | "fmt" 21 | "io" 22 | ) 23 | 24 | type MyCoolType struct { 25 | Name string 26 | a, b uint 27 | } 28 | 29 | // EncodeRLP writes x as RLP list [a, b] that omits the Name field. 30 | func (x *MyCoolType) EncodeRLP(w io.Writer) (err error) { 31 | // Note: the receiver can be a nil pointer. This allows you to 32 | // control the encoding of nil, but it also means that you have to 33 | // check for a nil receiver. 34 | if x == nil { 35 | err = Encode(w, []uint{0, 0}) 36 | } else { 37 | err = Encode(w, []uint{x.a, x.b}) 38 | } 39 | return err 40 | } 41 | 42 | func ExampleEncoder() { 43 | var t *MyCoolType // t is nil pointer to MyCoolType 44 | bytes, _ := EncodeToBytes(t) 45 | fmt.Printf("%v → %X\n", t, bytes) 46 | 47 | t = &MyCoolType{Name: "foobar", a: 5, b: 6} 48 | bytes, _ = EncodeToBytes(t) 49 | fmt.Printf("%v → %X\n", t, bytes) 50 | 51 | // Output: 52 | // → C28080 53 | // &{foobar 5 6} → C20506 54 | } 55 | -------------------------------------------------------------------------------- /service/doc.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | /* 4 | A service interacts with the outer world through an API that defines the 5 | methods that are callable from the outside. The service can hold data that 6 | will survive a restart of the cothority and instantiate any number of 7 | protocols before returning a value. 8 | 9 | This service defines two methods in the API: 10 | - Clock starts the 'template'-protocol and returns the run-time 11 | - Count returns how many times the 'template'-protocol has been run 12 | */ 13 | -------------------------------------------------------------------------------- /service/service_test.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/cypherium_private/mvp" 7 | "github.com/dedis/kyber/suites" 8 | "github.com/dedis/onet" 9 | "github.com/dedis/onet/log" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | var tSuite = suites.MustFind("Ed25519") 14 | 15 | func TestMain(m *testing.M) { 16 | log.MainTest(m) 17 | } 18 | 19 | // func TestService_Clock(t *testing.T) { 20 | 21 | // log.SetDebugVisible(5) 22 | 23 | // local := onet.NewTCPTest(tSuite) 24 | // // generate 5 hosts, they don't connect, they process messages, and they 25 | // // don't register the tree or entitylist 26 | // hosts, roster, tree := local.GenTree(5, true) 27 | // log.Lvl3(tree.Dump()) 28 | // defer local.CloseAll() 29 | 30 | // services := local.GetServices(hosts, templateID) 31 | 32 | // for _, s := range services { 33 | // log.Lvl2("Sending request to", s) 34 | // resp, err := s.(*Service).Clock( 35 | // &template.Clock{Roster: roster}, 36 | // ) 37 | // require.Nil(t, err) 38 | // require.Equal(t, resp.Children, len(roster.List)) 39 | // } 40 | // } 41 | 42 | func TestService_Count(t *testing.T) { 43 | 44 | log.SetDebugVisible(5) 45 | 46 | local := onet.NewTCPTest(tSuite) 47 | // generate 5 hosts, they don't connect, they process messages, and they 48 | // don't register the tree or entitylist 49 | hosts, roster, _ := local.GenTree(5, true) 50 | defer local.CloseAll() 51 | 52 | services := local.GetServices(hosts, templateID) 53 | 54 | for _, s := range services { 55 | log.Lvl2("Sending request to", s) 56 | resp, err := s.(*Service).Clock( 57 | &template.Clock{Roster: roster}, 58 | ) 59 | require.Nil(t, err) 60 | require.Equal(t, resp.Children, len(roster.List)) 61 | count, err := s.(*Service).Count(&template.Count{}) 62 | require.Nil(t, err) 63 | require.Equal(t, 1, count.Count) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /simulation/cypherium.toml: -------------------------------------------------------------------------------- 1 | Simulation = "cypherium" 2 | NumClientTxs = 2 3 | Servers = 9 4 | Bf = 8 5 | Rounds = 1 6 | CloseWait = 6000 7 | Suite = "Ed25519" 8 | 9 | Hosts, Blocksize, TimeoutMs, Fail 10 | 9, 8, 6000, 0 -------------------------------------------------------------------------------- /simulation/service.toml: -------------------------------------------------------------------------------- 1 | Simulation = "TemplateService" 2 | Servers = 8 3 | Bf = 2 4 | Rounds = 10 5 | CloseWait = 6000 6 | Suite = "Ed25519" 7 | 8 | Depth 9 | 1 10 | -------------------------------------------------------------------------------- /simulation/simul.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | // Service needs to be imported here to be instantiated. 5 | _ "github.com/cypherium_private/mvp/service" 6 | "github.com/dedis/onet/simul" 7 | ) 8 | 9 | func main() { 10 | simul.Start() 11 | } 12 | -------------------------------------------------------------------------------- /simulation/simul_test.go: -------------------------------------------------------------------------------- 1 | package main_test 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/dedis/onet/log" 7 | "github.com/dedis/onet/simul" 8 | ) 9 | 10 | // func TestMain(m *testing.M) { 11 | // log.MainTest(m) 12 | // } 13 | 14 | func TestSimulation(t *testing.T) { 15 | log.SetDebugVisible(5) 16 | simul.Start("cypherium.toml") 17 | } 18 | -------------------------------------------------------------------------------- /simulation/simulation: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cypherium/blockchain/658812165f756c124139ec2632fd4b308ede89d9/simulation/simulation -------------------------------------------------------------------------------- /struct.go: -------------------------------------------------------------------------------- 1 | package template 2 | 3 | /* 4 | This holds the messages used to communicate with the service over the network. 5 | */ 6 | 7 | import ( 8 | "github.com/cypherium_private/mvp/blockchain" 9 | "github.com/dedis/onet" 10 | "github.com/dedis/onet/network" 11 | ) 12 | 13 | // We need to register all messages so the network knows how to handle them. 14 | func init() { 15 | network.RegisterMessages( 16 | Count{}, CountReply{}, 17 | Clock{}, ClockReply{}, 18 | Transaction{}, TransReply{}, 19 | ) 20 | } 21 | 22 | const ( 23 | // ErrorParse indicates an error while parsing the protobuf-file. 24 | ErrorParse = iota + 4000 25 | ) 26 | 27 | // Clock will run the tepmlate-protocol on the roster and return 28 | // the time spent doing so. 29 | type Clock struct { 30 | Roster *onet.Roster 31 | } 32 | 33 | // ClockReply returns the time spent for the protocol-run. 34 | type ClockReply struct { 35 | Time float64 36 | Children int 37 | } 38 | 39 | // Count will return how many times the protocol has been run. 40 | type Count struct { 41 | } 42 | 43 | // CountReply returns the number of protocol-runs 44 | type CountReply struct { 45 | Count int 46 | } 47 | 48 | var MagicNum = [4]byte{0xF9, 0xBE, 0xB4, 0xD9} 49 | 50 | // ReadFirstNBlocks specifcy how many blocks in the the BlocksDir it must read 51 | // (so you only have to copy the first blocks to deterLab) 52 | const ReadFirstNBlocks = 400 53 | 54 | // Transaction will run the tepmlate-protocol on the roster and return 55 | // the result status. 56 | type Transaction struct { 57 | Roster *onet.Roster 58 | TransMsg []blockchain.STransaction 59 | } 60 | 61 | // TransReply return the result status. 62 | type TransReply struct { 63 | Time float64 64 | Children int 65 | Status int 66 | } 67 | -------------------------------------------------------------------------------- /trie/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package trie 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/cypherium_private/mvp/common" 23 | ) 24 | 25 | // MissingNodeError is returned by the trie functions (TryGet, TryUpdate, TryDelete) 26 | // in the case where a trie node is not present in the local database. It contains 27 | // information necessary for retrieving the missing node. 28 | type MissingNodeError struct { 29 | NodeHash common.Hash // hash of the missing node 30 | Path []byte // hex-encoded path to the missing node 31 | } 32 | 33 | func (err *MissingNodeError) Error() string { 34 | return fmt.Sprintf("missing trie node %x (path %x)", err.NodeHash, err.Path) 35 | } 36 | -------------------------------------------------------------------------------- /trie/node_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package trie 18 | 19 | import "testing" 20 | 21 | func TestCanUnload(t *testing.T) { 22 | tests := []struct { 23 | flag nodeFlag 24 | cachegen, cachelimit uint16 25 | want bool 26 | }{ 27 | { 28 | flag: nodeFlag{dirty: true, gen: 0}, 29 | want: false, 30 | }, 31 | { 32 | flag: nodeFlag{dirty: false, gen: 0}, 33 | cachegen: 0, cachelimit: 0, 34 | want: true, 35 | }, 36 | { 37 | flag: nodeFlag{dirty: false, gen: 65534}, 38 | cachegen: 65535, cachelimit: 1, 39 | want: true, 40 | }, 41 | { 42 | flag: nodeFlag{dirty: false, gen: 65534}, 43 | cachegen: 0, cachelimit: 1, 44 | want: true, 45 | }, 46 | { 47 | flag: nodeFlag{dirty: false, gen: 1}, 48 | cachegen: 65535, cachelimit: 1, 49 | want: true, 50 | }, 51 | } 52 | 53 | for _, test := range tests { 54 | if got := test.flag.canUnload(test.cachegen, test.cachelimit); got != test.want { 55 | t.Errorf("%+v\n got %t, want %t", test, got, test.want) 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /txpool/error.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package txpool 18 | 19 | import "errors" 20 | 21 | var ( 22 | // ErrKnownBlock is returned when a block to import is already known locally. 23 | ErrKnownBlock = errors.New("block already known") 24 | 25 | // ErrGasLimitReached is returned by the gas pool if the amount of gas required 26 | // by a transaction is higher than what's left in the block. 27 | ErrGasLimitReached = errors.New("gas limit reached") 28 | 29 | // ErrBlacklistedHash is returned if a block to import is on the blacklist. 30 | ErrBlacklistedHash = errors.New("blacklisted hash") 31 | 32 | // ErrNonceTooHigh is returned if the nonce of a transaction is higher than the 33 | // next one expected based on the local chain. 34 | ErrNonceTooHigh = errors.New("nonce too high") 35 | ) 36 | -------------------------------------------------------------------------------- /txpool/events.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package txpool 18 | 19 | import ( 20 | "github.com/cypherium_private/mvp/common" 21 | "github.com/cypherium_private/mvp/txpool/types" 22 | ) 23 | 24 | // TxPreEvent is posted when a transaction enters the transaction pool. 25 | type TxPreEvent struct{ Tx *types.Transaction } 26 | 27 | // PendingLogsEvent is posted pre mining and notifies of pending logs. 28 | type PendingLogsEvent struct { 29 | Logs []*types.Log 30 | } 31 | 32 | // PendingStateEvent is posted pre mining and notifies of pending state changes. 33 | type PendingStateEvent struct{} 34 | 35 | // NewMinedBlockEvent is posted when a block has been imported. 36 | type NewMinedBlockEvent struct{ Block *types.Block } 37 | 38 | // RemovedTransactionEvent is posted when a reorg happens 39 | type RemovedTransactionEvent struct{ Txs types.Transactions } 40 | 41 | // RemovedLogsEvent is posted when a reorg happens 42 | type RemovedLogsEvent struct{ Logs []*types.Log } 43 | 44 | type ChainEvent struct { 45 | Block *types.Block 46 | Hash common.Hash 47 | Logs []*types.Log 48 | } 49 | 50 | type ChainSideEvent struct { 51 | Block *types.Block 52 | } 53 | 54 | type ChainHeadEvent struct{ Block *types.Block } 55 | -------------------------------------------------------------------------------- /txpool/gaspool.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package txpool 18 | 19 | import ( 20 | "fmt" 21 | "math" 22 | ) 23 | 24 | // GasPool tracks the amount of gas available during execution of the transactions 25 | // in a block. The zero value is a pool with zero gas available. 26 | type GasPool uint64 27 | 28 | // AddGas makes gas available for execution. 29 | func (gp *GasPool) AddGas(amount uint64) *GasPool { 30 | if uint64(*gp) > math.MaxUint64-amount { 31 | panic("gas pool pushed above uint64") 32 | } 33 | *(*uint64)(gp) += amount 34 | return gp 35 | } 36 | 37 | // SubGas deducts the given amount from the pool if enough gas is 38 | // available and returns an error otherwise. 39 | func (gp *GasPool) SubGas(amount uint64) error { 40 | if uint64(*gp) < amount { 41 | return ErrGasLimitReached 42 | } 43 | *(*uint64)(gp) -= amount 44 | return nil 45 | } 46 | 47 | // Gas returns the amount of gas remaining in the pool. 48 | func (gp *GasPool) Gas() uint64 { 49 | return uint64(*gp) 50 | } 51 | 52 | func (gp *GasPool) String() string { 53 | return fmt.Sprintf("%d", *gp) 54 | } 55 | -------------------------------------------------------------------------------- /txpool/state/main_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package state 18 | 19 | import ( 20 | "testing" 21 | 22 | checker "gopkg.in/check.v1" 23 | ) 24 | 25 | func Test(t *testing.T) { checker.TestingT(t) } 26 | -------------------------------------------------------------------------------- /txpool/state/sync.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package state 18 | 19 | import ( 20 | "bytes" 21 | 22 | "github.com/cypherium_private/mvp/common" 23 | "github.com/cypherium_private/mvp/rlp" 24 | "github.com/cypherium_private/mvp/trie" 25 | ) 26 | 27 | // NewStateSync create a new state trie download scheduler. 28 | func NewStateSync(root common.Hash, database trie.DatabaseReader) *trie.TrieSync { 29 | var syncer *trie.TrieSync 30 | callback := func(leaf []byte, parent common.Hash) error { 31 | var obj Account 32 | if err := rlp.Decode(bytes.NewReader(leaf), &obj); err != nil { 33 | return err 34 | } 35 | syncer.AddSubTrie(obj.Root, 64, parent, nil) 36 | syncer.AddRawEntry(common.BytesToHash(obj.CodeHash), 64, parent) 37 | return nil 38 | } 39 | syncer = trie.NewTrieSync(root, database, callback) 40 | return syncer 41 | } 42 | -------------------------------------------------------------------------------- /txpool/types/derive_sha.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package types 18 | 19 | import ( 20 | "bytes" 21 | 22 | "github.com/cypherium_private/mvp/rlp" 23 | "github.com/cypherium_private/mvp/trie" 24 | ) 25 | 26 | type DerivableList interface { 27 | Len() int 28 | GetRlp(i int) []byte 29 | } 30 | 31 | func DeriveSha(list DerivableList) []byte { 32 | keybuf := new(bytes.Buffer) 33 | trie := new(trie.Trie) 34 | for i := 0; i < list.Len(); i++ { 35 | keybuf.Reset() 36 | rlp.Encode(keybuf, uint(i)) 37 | trie.Update(keybuf.Bytes(), list.GetRlp(i)) 38 | } 39 | // return trie.Hash() 40 | return trie.Bytes() 41 | } 42 | -------------------------------------------------------------------------------- /txpool/vm/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | /* 18 | Package vm implements the Ethereum Virtual Machine. 19 | 20 | The vm package implements one EVM, a byte code VM. The BC (Byte Code) VM loops 21 | over a set of bytes and executes them according to the set of rules defined 22 | in the Ethereum yellow paper. 23 | */ 24 | package vm 25 | -------------------------------------------------------------------------------- /txpool/vm/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package vm 18 | 19 | import "errors" 20 | 21 | var ( 22 | ErrOutOfGas = errors.New("out of gas") 23 | ErrCodeStoreOutOfGas = errors.New("contract creation code storage out of gas") 24 | ErrDepth = errors.New("max call depth exceeded") 25 | ErrTraceLimitReached = errors.New("the number of logs reached the specified limit") 26 | ErrInsufficientBalance = errors.New("insufficient balance for transfer") 27 | ErrContractAddressCollision = errors.New("contract address collision") 28 | ) 29 | -------------------------------------------------------------------------------- /txpool/vm/gas_table_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package vm 18 | 19 | import "testing" 20 | 21 | func TestMemoryGasCost(t *testing.T) { 22 | //size := uint64(math.MaxUint64 - 64) 23 | size := uint64(0xffffffffe0) 24 | v, err := memoryGasCost(&Memory{}, size) 25 | if err != nil { 26 | t.Error("didn't expect error:", err) 27 | } 28 | if v != 36028899963961341 { 29 | t.Errorf("Expected: 36028899963961341, got %d", v) 30 | } 31 | 32 | _, err = memoryGasCost(&Memory{}, size+1) 33 | if err == nil { 34 | t.Error("expected error") 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /txpool/vm/int_pool_verifier.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build VERIFY_EVM_INTEGER_POOL 18 | 19 | package vm 20 | 21 | import "fmt" 22 | 23 | const verifyPool = true 24 | 25 | func verifyIntegerPool(ip *intPool) { 26 | for i, item := range ip.pool.data { 27 | if item.Cmp(checkVal) != 0 { 28 | panic(fmt.Sprintf("%d'th item failed aggressive pool check. Value was modified", i)) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /txpool/vm/int_pool_verifier_empty.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build !VERIFY_EVM_INTEGER_POOL 18 | 19 | package vm 20 | 21 | const verifyPool = false 22 | 23 | func verifyIntegerPool(ip *intPool) {} 24 | -------------------------------------------------------------------------------- /txpool/vm/runtime/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // Package runtime provides a basic execution model for executing EVM code. 18 | package runtime 19 | -------------------------------------------------------------------------------- /txpool/vm/runtime/env.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package runtime 18 | 19 | import ( 20 | "github.com/cypherium_private/mvp/common" 21 | "github.com/cypherium_private/mvp/txpool" 22 | "github.com/cypherium_private/mvp/txpool/vm" 23 | ) 24 | 25 | func NewEnv(cfg *Config) *vm.EVM { 26 | context := vm.Context{ 27 | CanTransfer: txpool.CanTransfer, 28 | Transfer: txpool.Transfer, 29 | GetHash: func(uint64) common.Hash { return common.Hash{} }, 30 | 31 | Origin: cfg.Origin, 32 | Coinbase: cfg.Coinbase, 33 | BlockNumber: cfg.BlockNumber, 34 | Time: cfg.Time, 35 | Difficulty: cfg.Difficulty, 36 | GasLimit: cfg.GasLimit, 37 | GasPrice: cfg.GasPrice, 38 | } 39 | 40 | return vm.NewEVM(context, cfg.State, cfg.ChainConfig, cfg.EVMConfig) 41 | } 42 | -------------------------------------------------------------------------------- /txpool/vm/runtime/fuzz.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | // +build gofuzz 18 | 19 | package runtime 20 | 21 | // Fuzz is the basic entry point for the go-fuzz tool 22 | // 23 | // This returns 1 for valid parsable/runable code, 0 24 | // for invalid opcode. 25 | func Fuzz(input []byte) int { 26 | _, _, err := Execute(input, input, &Config{ 27 | GasLimit: 3000000, 28 | }) 29 | 30 | // invalid opcode 31 | if err != nil && len(err.Error()) > 6 && string(err.Error()[:7]) == "invalid" { 32 | return 0 33 | } 34 | 35 | return 1 36 | } 37 | -------------------------------------------------------------------------------- /txpool/vm/runtime/runtime_example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package runtime_test 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/cypherium_private/mvp/common" 23 | "github.com/cypherium_private/mvp/txpool/vm/runtime" 24 | ) 25 | 26 | func ExampleExecute() { 27 | ret, _, err := runtime.Execute(common.Hex2Bytes("6060604052600a8060106000396000f360606040526008565b00"), nil, nil) 28 | if err != nil { 29 | fmt.Println(err) 30 | } 31 | fmt.Println(ret) 32 | // Output: 33 | // [96 96 96 64 82 96 8 86 91 0] 34 | } 35 | -------------------------------------------------------------------------------- /txpool/vm/stack_table.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package vm 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/cypherium_private/mvp/params" 23 | ) 24 | 25 | func makeStackFunc(pop, push int) stackValidationFunc { 26 | return func(stack *Stack) error { 27 | if err := stack.require(pop); err != nil { 28 | return err 29 | } 30 | 31 | if stack.len()+push-pop > int(params.StackLimit) { 32 | return fmt.Errorf("stack limit reached %d (%d)", stack.len(), params.StackLimit) 33 | } 34 | return nil 35 | } 36 | } 37 | 38 | func makeDupStackFunc(n int) stackValidationFunc { 39 | return makeStackFunc(n, n+1) 40 | } 41 | 42 | func makeSwapStackFunc(n int) stackValidationFunc { 43 | return makeStackFunc(n, n) 44 | } 45 | --------------------------------------------------------------------------------