├── test-data ├── dat │ ├── alphabet │ │ ├── a │ │ ├── b │ │ ├── c │ │ ├── d │ │ ├── e │ │ ├── f │ │ └── .dat │ │ │ ├── metadata.latest │ │ │ ├── metadata.ogd │ │ │ ├── content.key │ │ │ ├── content.tree │ │ │ ├── metadata.data │ │ │ ├── metadata.key │ │ │ ├── metadata.tree │ │ │ ├── content.bitfield │ │ │ ├── content.secret_key │ │ │ ├── content.signatures │ │ │ ├── metadata.bitfield │ │ │ ├── metadata.secret_key │ │ │ └── metadata.signatures │ ├── tree │ │ ├── .dat │ │ │ ├── metadata.ogd │ │ │ ├── metadata.latest │ │ │ ├── content.key │ │ │ ├── content.tree │ │ │ ├── metadata.key │ │ │ ├── metadata.data │ │ │ ├── metadata.tree │ │ │ ├── content.bitfield │ │ │ ├── metadata.bitfield │ │ │ ├── content.secret_key │ │ │ ├── content.signatures │ │ │ ├── metadata.secret_key │ │ │ └── metadata.signatures │ │ ├── README.md │ │ ├── datapackage.json │ │ ├── Animalia │ │ │ └── Chordata │ │ │ │ └── Mammalia │ │ │ │ └── Carnivora │ │ │ │ ├── Caniformia │ │ │ │ └── Mustelidae │ │ │ │ │ └── Lutrinae │ │ │ │ │ └── Enhydra │ │ │ │ │ └── E_lutris.txt │ │ │ │ └── Feliformia │ │ │ │ └── Felidae │ │ │ │ └── Felis │ │ │ │ └── F_silvestris.txt │ │ └── Fungi │ │ │ └── Basidiomycota │ │ │ └── Agaricormycetes │ │ │ └── Cantharellales │ │ │ └── Cantharellaceae │ │ │ └── Cantharellus │ │ │ ├── C_cibarius.txt │ │ │ └── C_appalachiensis.txt │ ├── removal │ │ ├── .dat │ │ │ ├── metadata.latest │ │ │ ├── metadata.ogd │ │ │ ├── content.key │ │ │ ├── content.tree │ │ │ ├── metadata.data │ │ │ ├── metadata.key │ │ │ ├── metadata.tree │ │ │ ├── content.bitfield │ │ │ ├── content.secret_key │ │ │ ├── content.signatures │ │ │ ├── metadata.bitfield │ │ │ └── metadata.signatures │ │ ├── final.txt │ │ └── README.md │ ├── simple │ │ ├── .dat │ │ │ ├── metadata.latest │ │ │ ├── metadata.ogd │ │ │ ├── content.key │ │ │ ├── content.tree │ │ │ ├── metadata.key │ │ │ ├── metadata.data │ │ │ ├── metadata.tree │ │ │ ├── content.bitfield │ │ │ ├── metadata.bitfield │ │ │ ├── content.secret_key │ │ │ ├── content.signatures │ │ │ ├── metadata.secret_key │ │ │ └── metadata.signatures │ │ └── README.md │ └── README.md └── sleep │ └── empty │ ├── empty.sleep │ ├── empty.hexdump │ └── empty.py ├── notes ├── bugs.txt ├── refs.md ├── spec_todo.txt ├── new_apis.md ├── crypto.txt ├── process.md ├── drive.md ├── upstream_behavior.txt ├── register.md ├── sleep.md ├── network.md ├── crypto │ ├── ipython_log.py │ └── notes.txt ├── architecture.md └── dat-spec-thoughts.md ├── THOUGHTS ├── .gitignore ├── Cargo.toml ├── src ├── metadata_msgs.proto ├── discovery.rs ├── bitfield.rs ├── lib.rs ├── helpers.rs ├── network_msgs.proto ├── bin │ ├── geniza-net.rs │ ├── geniza.rs │ ├── geniza-sleep.rs │ └── geniza-drive.rs ├── peer.rs ├── sleep_file.rs ├── synchronizer.rs ├── protocol.rs └── sleep_register.rs ├── .travis.yml ├── README.md ├── TODO ├── Cargo.lock └── LICENSE /test-data/dat/alphabet/a: -------------------------------------------------------------------------------- 1 | a -------------------------------------------------------------------------------- /test-data/dat/alphabet/b: -------------------------------------------------------------------------------- 1 | b -------------------------------------------------------------------------------- /test-data/dat/alphabet/c: -------------------------------------------------------------------------------- 1 | c -------------------------------------------------------------------------------- /test-data/dat/alphabet/d: -------------------------------------------------------------------------------- 1 | d -------------------------------------------------------------------------------- /test-data/dat/alphabet/e: -------------------------------------------------------------------------------- 1 | e -------------------------------------------------------------------------------- /test-data/dat/alphabet/f: -------------------------------------------------------------------------------- 1 | f -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.ogd: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.latest: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.ogd: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/metadata.latest: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/metadata.ogd: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.latest: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.ogd: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.latest: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-data/dat/tree/README.md: -------------------------------------------------------------------------------- 1 | 2 | Welcome to the Tree of Life! 3 | -------------------------------------------------------------------------------- /test-data/dat/tree/datapackage.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tree test dat" 3 | } 4 | -------------------------------------------------------------------------------- /test-data/dat/removal/final.txt: -------------------------------------------------------------------------------- 1 | 2 | My Manifesto 3 | 4 | - point the first 5 | - point the last 6 | -------------------------------------------------------------------------------- /test-data/sleep/empty/empty.sleep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/sleep/empty/empty.sleep -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/content.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/content.key -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/content.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/content.tree -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/metadata.key -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/content.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/content.key -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/content.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/content.key -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/content.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/content.tree -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/metadata.key -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.data: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/metadata.data -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/metadata.tree -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/content.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/content.key -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/content.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/content.tree -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.data: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/metadata.data -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/metadata.key -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/metadata.tree -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/content.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/content.tree -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/metadata.data: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/metadata.data -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/metadata.key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/metadata.key -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/metadata.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/metadata.tree -------------------------------------------------------------------------------- /test-data/dat/removal/README.md: -------------------------------------------------------------------------------- 1 | 2 | This dat contains a manifesto, which has been edited (under the draft folder), then deleted. 3 | -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.data: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/metadata.data -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.tree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/metadata.tree -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/content.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/content.bitfield -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/metadata.bitfield -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/content.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/content.bitfield -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/content.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/content.bitfield -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/metadata.bitfield -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/content.secret_key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/content.secret_key -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/content.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/content.signatures -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.secret_key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/metadata.secret_key -------------------------------------------------------------------------------- /test-data/dat/tree/.dat/metadata.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/tree/.dat/metadata.signatures -------------------------------------------------------------------------------- /test-data/dat/tree/Animalia/Chordata/Mammalia/Carnivora/Caniformia/Mustelidae/Lutrinae/Enhydra/E_lutris.txt: -------------------------------------------------------------------------------- 1 | Sea Otters are the best! 2 | -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/content.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/content.bitfield -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/content.secret_key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/content.secret_key -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/content.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/content.signatures -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/metadata.bitfield -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/content.secret_key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/content.secret_key -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/content.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/content.signatures -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/metadata.bitfield: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/metadata.bitfield -------------------------------------------------------------------------------- /test-data/dat/removal/.dat/metadata.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/removal/.dat/metadata.signatures -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/content.secret_key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/content.secret_key -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/content.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/content.signatures -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.secret_key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/metadata.secret_key -------------------------------------------------------------------------------- /test-data/dat/simple/.dat/metadata.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/simple/.dat/metadata.signatures -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.secret_key: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/metadata.secret_key -------------------------------------------------------------------------------- /test-data/dat/alphabet/.dat/metadata.signatures: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnewbold/geniza/HEAD/test-data/dat/alphabet/.dat/metadata.signatures -------------------------------------------------------------------------------- /test-data/dat/tree/Fungi/Basidiomycota/Agaricormycetes/Cantharellales/Cantharellaceae/Cantharellus/C_cibarius.txt: -------------------------------------------------------------------------------- 1 | Chanterelles, yummy yummy. 2 | -------------------------------------------------------------------------------- /notes/bugs.txt: -------------------------------------------------------------------------------- 1 | 2 | possible upstream bug: 3 | => sync data in subdir 4 | => stop client 5 | => remove entire dir 6 | => doesn't `del` on later sync 7 | -------------------------------------------------------------------------------- /test-data/dat/tree/Animalia/Chordata/Mammalia/Carnivora/Feliformia/Felidae/Felis/F_silvestris.txt: -------------------------------------------------------------------------------- 1 | Kittens, so かわいい! 2 | 3 | Are there more cat species? Probably! 4 | -------------------------------------------------------------------------------- /test-data/dat/tree/Fungi/Basidiomycota/Agaricormycetes/Cantharellales/Cantharellaceae/Cantharellus/C_appalachiensis.txt: -------------------------------------------------------------------------------- 1 | You know, from the Appalachian Mountains! 2 | -------------------------------------------------------------------------------- /test-data/sleep/empty/empty.hexdump: -------------------------------------------------------------------------------- 1 | 00000000: 0502 57ff 0000 0100 0000 0000 0000 0000 ..W............. 2 | 00000010: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 3 | -------------------------------------------------------------------------------- /notes/refs.md: -------------------------------------------------------------------------------- 1 | 2 | Decent "Original" Bittorrent client description: 3 | 4 | https://github.com/mgp/coding-in-the-real-world/blob/master/manuscript/bittorrent-client-case-study.md 5 | 6 | -------------------------------------------------------------------------------- /test-data/dat/simple/README.md: -------------------------------------------------------------------------------- 1 | 2 | This is a self-referential dat with a single file (this README). 3 | 4 | dat://cb1e8d65f3c6242db90bfd99accaf47930ea3ff6c852fb50caaa548c9cdcb8b7 5 | -------------------------------------------------------------------------------- /notes/spec_todo.txt: -------------------------------------------------------------------------------- 1 | 2 | Extra things learned: 3 | - metadata secret keys live in ~/.dat/secret_keys/... 4 | - metadata.ogd indicates "original dat", meaning secret key should be present 5 | - metadata.latest file exists sometimes... 6 | 7 | -------------------------------------------------------------------------------- /THOUGHTS: -------------------------------------------------------------------------------- 1 | 2 | Should probably stick with simple hyperdrives only in synchronizer 3 | implementation, instead of biting off arbitary feeds-per-peer. 4 | 5 | Was intenting to abandon this project, but still sort of thinking of using 6 | crossbeam-channels or actix to hack something out. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | papers/ 2 | target/ 3 | scratch/ 4 | **/*.rs.bk 5 | *.o 6 | *.a 7 | *.pyc 8 | #*# 9 | *~ 10 | *.swp 11 | .* 12 | *.tmp 13 | *.old 14 | *.profile 15 | *.bkp 16 | *.bak 17 | [Tt]humbs.db 18 | *.DS_Store 19 | build/ 20 | _build/ 21 | src/build/ 22 | *.log 23 | 24 | # Don't ignore dat/sleep files for this repo in particular 25 | !.dat 26 | 27 | # Don't ignore this file itself 28 | !.gitignore 29 | !.travis.yml 30 | -------------------------------------------------------------------------------- /notes/new_apis.md: -------------------------------------------------------------------------------- 1 | 2 | ## HOWTO: clone drive from scratch 3 | 4 | - create empty metadata register (on disk) from key (to ensure we can?) 5 | - do discovery to find peers 6 | - from first peer, discover data key 7 | - create data register 8 | - create drive from empty registers 9 | - create synchronizer from all the above 10 | - ... off it goes 11 | 12 | ## HOWTO: sync existing drive 13 | 14 | - open the drive (on disk) 15 | - create synchronizer from drive 16 | - synchronizer does discovery of peers using metadata key (based on config) 17 | - ... off it goes 18 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "geniza" 3 | version = "0.1.0" 4 | authors = ["Bryan Newbold "] 5 | license = "GPL-3.0" 6 | 7 | [dependencies] 8 | rust-crypto = "^0.2" 9 | integer-encoding = "^1.0" 10 | clap = "2" 11 | error-chain = "0.7" 12 | env_logger = "0.3" 13 | rand = "0.3" 14 | protobuf = "1.3" 15 | log = "0.3" 16 | sodiumoxide = "0.0.16" 17 | bit_field = "0.9" 18 | bit-vec = "0.4.4" 19 | data-encoding = "2.0" 20 | chan = "0.1.20" 21 | chan-signal = "0.3.1" 22 | resolve = "0.2" 23 | 24 | [dev-dependencies] 25 | tempdir = "0.3" 26 | assert_cli = "0.5" 27 | -------------------------------------------------------------------------------- /test-data/sleep/empty/empty.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """This script generates empty.sleep""" 4 | 5 | # Create file in binary mode 6 | f = open('empty.sleep', 'wb') 7 | 8 | # Move to begining, set size 9 | f.seek(0) 10 | f.truncate(32) 11 | 12 | # Write header, with 0xFF as the dat file type 13 | f.write(b'\x05\x02\x57\xFF') 14 | 15 | # Version 0 16 | f.write(b'\x00') 17 | 18 | # One-byte entry size 19 | f.write(b'\x00\x01') 20 | 21 | # No Algorithm name 22 | f.write(b'\x00') 23 | for i in range(24): 24 | f.write(b'\x00') 25 | 26 | assert(f.tell() == 32) 27 | f.close() 28 | -------------------------------------------------------------------------------- /notes/crypto.txt: -------------------------------------------------------------------------------- 1 | 2 | Like many libsodium wrappers, and apparently *all* reasonable Rust bindings, 3 | sodiumoxcide does not expose the `crypto_stream_xsalsa20_xor_ic` function, 4 | necessary to use libsodium in an endless steam configuration. 5 | 6 | https://nacl.cr.yp.to/stream.html 7 | https://github.com/maidsafe/rust_sodium 8 | https://groups.google.com/forum/#!original/boring-crypto/BpUmNMXKMYQ/EEwAIeQdjacJ 9 | 10 | 11 | TLS is a pain, but if it (or some other standard) was used instead of the 12 | current libsodium, it might be possible in the future to get kernel-mode 13 | encryption going. 14 | 15 | -------------------------------------------------------------------------------- /test-data/dat/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## simple 3 | 4 | This is a simple (but not the simplest possible) dat archive: a single short 5 | README file, which is added in one version and modified in the second (to 6 | include a self-reference to the dat address). 7 | 8 | ## alphabet 9 | 10 | This dat archive is intended to match the content tree examples from the 11 | `hypercore` registry. 12 | 13 | To generate single-character files with no trailing newline: 14 | 15 | echo -n 'a' > a 16 | echo -n 'b' > b 17 | echo -n 'c' > c 18 | echo -n 'd' > d 19 | echo -n 'e' > e 20 | echo -n 'f' > f 21 | 22 | ## tree 23 | 24 | This archive has a bunch of deeply nested folders, to demonstrate hyperdrive 25 | lookup behavior. 26 | -------------------------------------------------------------------------------- /notes/process.md: -------------------------------------------------------------------------------- 1 | 2 | This is an ordered list of testable steps to get to a minimal dat client in 3 | just about any language. 4 | 5 | sleep 6 | read/write headers 7 | read/write individual elements as raw bytes 8 | read/write contiguous batches 9 | 10 | registers 11 | read elements by index 12 | verify signature by index (not leaves) 13 | append elements 14 | 15 | drive 16 | data register to a single file 17 | single file to a data register 18 | print metadata tree ("ls") 19 | create metadata tree for a directory 20 | directory to metadata+data registers 21 | registers to directory 22 | 23 | sync 24 | send/receive messages to a known host 25 | pull register from a known host 26 | wrapper command 27 | 28 | 29 | 30 | 31 | Shortcuts: 32 | key/value store instead of SLEEP files 33 | pull/read/to-file only 34 | don't verify any hashes (!) 35 | -------------------------------------------------------------------------------- /src/metadata_msgs.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto2"; 2 | 3 | // File copied from: https://github.com/mafintosh/hyperdrive/blob/master/lib/messages.js 4 | // Copyright (c) 2015 Mathias Buus 5 | // MIT License (MIT) 6 | 7 | 8 | message Index { 9 | required string type = 1; 10 | optional bytes content = 2; 11 | } 12 | 13 | message Stat { 14 | required uint32 mode = 1; 15 | optional uint32 uid = 2; 16 | optional uint32 gid = 3; 17 | optional uint64 size = 4; 18 | optional uint64 blocks = 5; 19 | optional uint64 offset = 6; 20 | optional uint64 byteOffset = 7; 21 | optional uint64 mtime = 8; 22 | optional uint64 ctime = 9; 23 | } 24 | 25 | // File copied from: https://github.com/mafintosh/append-tree/blob/master/schema.proto 26 | // Copyright (c) 2015 Mathias Buus 27 | // MIT License (MIT) 28 | 29 | message Node { 30 | required string name = 1; 31 | optional bytes value = 2; 32 | optional bytes paths = 3; 33 | } 34 | -------------------------------------------------------------------------------- /notes/drive.md: -------------------------------------------------------------------------------- 1 | 2 | First varint is a header. Lowest bit of header is "endsWithSeq". 3 | 4 | When expanding, if "endsWithSeq", is set, add the current index to *every* 5 | level of the array? 6 | 7 | When adding, the current index is always added at every stage of the path. 8 | 9 | In the index, include one entry for subdirectories; take the newest element of 10 | the subdirectory as that entry (which might itself be a deeper nested 11 | subdirectory entry) 12 | 13 | There seem to be extra empty arrays everywhere? not sure what's up with that, 14 | maybe I have an off-by-one. 15 | 16 | The current path counts as an entry (eg, "/README" decomposes to "/" and 17 | "README", two entries). I'm not sure why... so directories can have entries? 18 | 19 | Entry indexes are effectively 1-based (0 is the pubkey entry); don't correct 20 | for this. 21 | 22 | In children: 23 | - Changes/edits to a path entirely replace the old entry index with the new 24 | index. 25 | - removals of an entry are done by writing a new entry with the same path, no 26 | stat data, and with all child paths removed (of this index and the old 27 | index). 28 | -------------------------------------------------------------------------------- /notes/upstream_behavior.txt: -------------------------------------------------------------------------------- 1 | 2 | hypercore: 'Request' without 'Have' crashes dat, despite whitepaper saying "You 3 | should only send Have messages to peers who have expressed interest in this 4 | region with Want messages.": 5 | 6 | /usr/lib/node_modules/dat/node_modules/hypercore/lib/replicate.js:119 7 | if (!self.remoteBitfield.set(request.index, true)) return 8 | ^ 9 | 10 | TypeError: Cannot read property 'set' of null 11 | at onvalue (/usr/lib/node_modules/dat/node_modules/hypercore/lib/replicate.js:119:33) 12 | at onread (/usr/lib/node_modules/dat/node_modules/random-access-file/index.js:130:14) 13 | at FSReqWrap.wrapper [as oncomplete] (fs.js:629:17) 14 | 15 | dat-network seems to keep trying to send data every 30 seconds even if remote 16 | client has disconnected: 17 | 18 | [...] 19 | dat-network Uploaded data: 984105 +500ms 20 | dat-network Uploaded data: 984105 +500ms 21 | dat-network Uploaded data: 984105 +501ms 22 | dat-network Uploaded data: 984105 +499ms 23 | dat-network Uploaded data: 984105 +501ms 24 | dat-network Uploaded data: 984105 +500ms 25 | dat-network Uploaded data: 984105 +500ms 26 | [...] 27 | 28 | -------------------------------------------------------------------------------- /notes/register.md: -------------------------------------------------------------------------------- 1 | 2 | ### Register File Types 3 | 4 | tree: SLEEP merkel tree 5 | magic: 0x05025702 6 | entry-size: 40 bytes 7 | algorithm name: 'BLAKE2b' (len=7) 8 | entry: 32-byte BLAKE2b node hash + 8-byte Uint64BE length 9 | signatures: SLEEP array 10 | magic: 0x05025701 11 | entry-size: 65 12 | algorithm name: 'Ed25519' (len=7) 13 | entry: 64-byte Ed25519 signature 14 | bitfield: SLEEP array of bitfields 15 | magic: 0x05025700 16 | entry-size: 3328 17 | algorithm name: '' (len=0) 18 | entry: 1024 bytes data, 2048 bytes tree, 256 bitfield 19 | key: public key 20 | no header, raw bytes 21 | data 22 | no header, raw bytes, concatonated 23 | 24 | ### Register API 25 | 26 | SleepDirectoryRegister struct 27 | open(directory, prefix) 28 | create(directory, prefix, options) 29 | 30 | file handles for tree, sig, bitfield, data; key is write-once 31 | 32 | has(index) -> bool 33 | has_all() -> bool 34 | has_range(start, end) -> bool 35 | get(index) -> data (arbitrary length) 36 | append(entry) -> index written 37 | len() -> u64 38 | len_bytes() -> u64 39 | verify() -> bool (verifies merkel tree against data, and signatures) 40 | check() -> bool (quick consistency check of lengths, etc) 41 | writable() -> bool 42 | 43 | read_block(start, end) -> read api implementer 44 | 45 | -------------------------------------------------------------------------------- /notes/sleep.md: -------------------------------------------------------------------------------- 1 | 2 | ### Binary Header 3 | 4 | Fixed 32-bytes 5 | 6 | ----------------------------------------------------------------- 7 | | MAGIC | 8 | ----------------------------------------------------------------- 9 | | VERSION (0) | ENTRY SIZE (uint16BE) | ALGO NAME LEN | 10 | ----------------------------------------------------------------- 11 | | | 12 | | | 13 | | | 14 | | ALGORITHM NAME (lower-case string) | 15 | | | 16 | | | 17 | ----------------------------------------------------------------- 18 | 19 | 20 | MAGIC and ENTRY SIZE are both "big-endian", meaning that the "first" (aka 21 | "most-significant" byte is in the "first" memory location (aka, "lowest 22 | address"). 23 | 24 | PREFIX LEN is max 24 (bytes) 25 | 26 | offset: 32 + entrySize * entryIndex 27 | count: (fileSize - 32) / entrySize 28 | 29 | 30 | ### SLEEP API 31 | 32 | SleepStorage trait 33 | SleepFile struct/impl 34 | 35 | get_magic() -> u32 36 | get_algorithm() -> &str 37 | read(index) -> &bytes[] 38 | write(index, &bytes[]) 39 | len() -> u64 40 | 41 | First time around just do regular file seek() stuff 42 | -------------------------------------------------------------------------------- /notes/network.md: -------------------------------------------------------------------------------- 1 | 2 | ### dat-specific configuration 3 | 4 | Default servers are specified in the `dat-swarm-defaults` module. As of 5 | November 2017, they are: 6 | 7 | Domain (for mDNS, centralized DNS): 8 | dat.local 9 | 10 | DNS Servers (centralized lookup): 11 | discovery1.publicbits.org 12 | discovery2.publicbits.org 13 | 14 | DHT Bootstrap Servers: 15 | bootstrap1.publicbits.org:6881 16 | bootstrap2.publicbits.org:6881 17 | bootstrap3.publicbits.org:6881 18 | bootstrap4.publicbits.org:6881 19 | 20 | ### mDNS and Centralized DNS Discovery 21 | 22 | `dns-discovery` node module. 23 | 24 | Refresh period: 1 minute 25 | 26 | Take the first 40 hex characters (lowercase; 20 bytes if decoded) of the 27 | discovery key (a BLAKE2b hash) instead of a SHA1 hash (which is what bittorrent 28 | uses). Prepend this to the domain (`dat.local` in the case of dat). 29 | 30 | There are both SRV and TXT records. SRV is straightforward, a response like: 31 | 32 | 0 0 44113 172.19.0.4. 33 | 34 | TXT uses some un-documented token scheme... maybe mostly for mDNS, to update or 35 | "unannounce" records? Eg: 36 | 37 | "token=kZabfUWLUw5A4E/EXM3+ka7UybMN95QJjqPk1iGmb0M=" "peers=rBMABKxR" 38 | 39 | Example lookup: 40 | 41 | dig @discovery1.publicbits.org 905fd1b6504698425e8bec3dbb77d757e281d505.dat.local SRV 42 | 43 | Note that you might need to do lookup on *both* servers? Results can be 44 | different from either individually. 45 | 46 | ### DHT Discovery 47 | 48 | `discovery-channel` 49 | 50 | Refresh period: 10 minutes 51 | 52 | -------------------------------------------------------------------------------- /src/discovery.rs: -------------------------------------------------------------------------------- 1 | 2 | use errors::*; 3 | use std::net::{IpAddr, SocketAddr}; 4 | use make_discovery_key; 5 | use data_encoding::HEXLOWER; 6 | use resolve::{DnsConfig, DnsResolver, resolve_host}; 7 | use resolve::record::Srv; 8 | 9 | pub fn discover_peers_dns(dat_key: &[u8]) -> Result> { 10 | 11 | let dk = make_discovery_key(dat_key); 12 | let dk_hex = HEXLOWER.encode(&dk); 13 | let dk_name = format!("{}.dat.local", &dk_hex[0..40]); 14 | info!("discovering peers using DNS: {}", dk_name); 15 | 16 | let dns1: Vec = resolve_host("discovery1.publicbits.org")?.collect(); 17 | let dns2: Vec = resolve_host("discovery2.publicbits.org")?.collect(); 18 | 19 | let default_config = DnsConfig::load_default()?; 20 | let config = DnsConfig { 21 | name_servers: vec![ 22 | SocketAddr::from((dns1[0], 53)), 23 | SocketAddr::from((dns2[0], 53))], 24 | search: vec!["dat.local".to_string()], 25 | n_dots: default_config.n_dots, 26 | timeout: default_config.timeout, 27 | attempts: default_config.attempts, 28 | rotate: true, 29 | use_inet6: false, 30 | }; 31 | 32 | let resolver = DnsResolver::new(config)?; 33 | 34 | let peers: Vec = resolver.resolve_record(&dk_name)?; 35 | // target (IP addresses) are returned with a trailing period that must be stripped 36 | let peers: Vec = peers.into_iter().map(|r| format!("{}:{}", &r.target[0..(r.target.len()-1)], r.port).parse().unwrap()).collect(); 37 | info!("found peers: {:?}", peers); 38 | Ok(peers) 39 | } 40 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Based on the "trust" template v0.1.1 2 | # https://github.com/japaric/trust/tree/v0.1.1 3 | 4 | dist: trusty 5 | language: rust 6 | services: docker 7 | sudo: required 8 | 9 | rust: 10 | - stable 11 | #- 1.19.0 12 | #- nightly 13 | 14 | env: 15 | global: 16 | - CRATE_NAME=geniza 17 | 18 | matrix: 19 | include: 20 | # Linux 21 | #- env: TARGET=i686-unknown-linux-gnu 22 | - env: TARGET=x86_64-unknown-linux-gnu 23 | #- env: TARGET=x86_64-unknown-linux-musl 24 | 25 | # OSX 26 | #- env: TARGET=x86_64-apple-darwin 27 | # os: osx 28 | 29 | # *BSD 30 | #- env: TARGET=x86_64-unknown-netbsd DISABLE_TESTS=1 31 | 32 | # Other architectures 33 | #- env: TARGET=aarch64-unknown-linux-gnu 34 | #- env: TARGET=armv7-unknown-linux-gnueabihf 35 | 36 | # Testing other channels 37 | #- env: TARGET=x86_64-unknown-linux-gnu 38 | # rust: nightly 39 | 40 | before_install: 41 | 42 | # Need to install libsodium-dev, which isn't in the system apt repo 43 | install: 44 | - sudo apt install pkg-config build-essential libtool autotools-dev automake check git yasm pkg-config 45 | - wget http://archive.ubuntu.com/ubuntu/pool/universe/libs/libsodium/libsodium18_1.0.8-5_amd64.deb 46 | - wget http://archive.ubuntu.com/ubuntu/pool/universe/libs/libsodium/libsodium-dev_1.0.8-5_amd64.deb 47 | - sudo dpkg -i libsodium-dev_1.0.8-5_amd64.deb libsodium18_1.0.8-5_amd64.deb 48 | - source ~/.cargo/env || true 49 | 50 | cache: cargo 51 | before_cache: 52 | # Travis can't cache files that are not readable by "others" 53 | - chmod -R a+r $HOME/.cargo 54 | 55 | branches: 56 | only: 57 | # release tags 58 | - /^v\d+\.\d+\.\d+.*$/ 59 | - master 60 | 61 | notifications: 62 | email: 63 | on_success: never 64 | -------------------------------------------------------------------------------- /src/bitfield.rs: -------------------------------------------------------------------------------- 1 | 2 | use errors::*; 3 | use integer_encoding::VarInt; 4 | use bit_field::BitArray; 5 | use network_msgs::Have; 6 | 7 | pub struct Bitfield { 8 | inner: Vec, 9 | } 10 | 11 | impl Bitfield { 12 | 13 | pub fn from_have_msg(_msg: &Have) -> Bitfield { 14 | unimplemented!() 15 | } 16 | 17 | pub fn get(&self, _index: u64) -> Result { 18 | unimplemented!() 19 | } 20 | } 21 | 22 | pub fn decode_bitfield(raw_bf: &[u8]) -> Result> { 23 | let mut offset = 0; // byte offset that we have read up to 24 | if raw_bf.len() < 1 { 25 | bail!("Expected (varint-encoded) bitfield to have len>=1"); 26 | } 27 | let mut bit_array: Vec = vec![]; 28 | while offset < raw_bf.len() { 29 | let (header, inc): (u64, usize) = VarInt::decode_var(&raw_bf[offset..]); 30 | offset += inc; 31 | 32 | if (header & 0x01) == 0x01 { 33 | // compressed 34 | let bit = (header & 0x02) == 0x02; 35 | let run_len = header >> 2; 36 | if bit { 37 | bit_array.append(&mut vec![0xFF; run_len as usize]); 38 | } else { 39 | bit_array.append(&mut vec![0x00; run_len as usize]); 40 | } 41 | } else { 42 | // uncompressed 43 | let byte_count = header >> 1; 44 | let mut data = raw_bf[offset..(offset + byte_count as usize)].to_vec(); 45 | bit_array.append(&mut data); 46 | offset += byte_count as usize; 47 | } 48 | } 49 | // XXX: HACK 50 | bit_array.reverse(); 51 | return Ok(bit_array); 52 | } 53 | 54 | /// Finds the index of the lowest bit 55 | pub fn max_high_bit(bf: &[u8]) -> u64 { 56 | // XXX: HACK, going backwards 57 | for i in 0..bf.bit_length() { 58 | if bf.get_bit(i) { 59 | return (bf.bit_length() - i - 1) as u64; 60 | } 61 | } 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /notes/crypto/ipython_log.py: -------------------------------------------------------------------------------- 1 | # IPython log file 2 | 3 | import pysodium 4 | import base64 5 | import pyblake2 6 | 7 | pub_key = "yx6NZfPGJC25C/2ZrMr0eTDqP/bIUvtQyqpUjJzcuLc=" 8 | base64.b16encode(base64.b64decode(pub_key)).lower() 9 | pub_key = base64.b64decode(pub_key) 10 | secret_key = "qzvSkJMQeWw2rGb4W+xbGNTgk5dEkiViOtq5niOkEiTLHo1l88YkLbkL/ZmsyvR5MOo/9shS+1DKqlSMnNy4tw==" 11 | base64.b16encode(base64.b64decode(secret_key)).lower() 12 | secret_key = base64.b64decode(secret_key) 13 | 14 | h = pyblake2.blake2b(data=b"hypercore", key=pub_key, digest_size=32) 15 | h.hexdigest() 16 | 17 | base64.b16encode(bytearray([43, 235, 230, 134, 54, 24, 197, 134, 8, 109, 37, 32, 170, 13, 19, 218, 102, 107, 0, 46, 90, 210, 177, 98, 35, 161, 91, 193, 85, 134, 241, 228, 0, 0, 0, 0, 0, 0, 0, 204])).lower() 18 | 19 | h = pyblake2.blake2b(digest_size=32) 20 | h.update([2]) 21 | h.update(bytearray([0x02])) 22 | h.update(base64.b16decode("67179c243b387b7c7c420bd7bdc69d35c061b979bb365f9cc07b4527eeddeefa".upper())) 23 | h.update(bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) 24 | h.update(bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42])) 25 | h.hexdigest() 26 | 27 | base64.b16encode(pysodium.crypto_sign_detached(h.digest(), secret_key)).lower() 28 | 29 | h = pyblake2.blake2b(digest_size=32) 30 | h.update(bytearray([0x02])) 31 | h.update(base64.b16decode("ab27d45f509274ce0d08f4f09ba2d0e0d8df61a0c2a78932e81b5ef26ef398df".upper())) 32 | h.update(bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) 33 | h.update(bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01])) 34 | h.hexdigest() 35 | 36 | sk = base64.b16decode("53729c0311846cca9cc0eded07aaf9e6689705b6a0b1bb8c3a2a839b72fda3839718a1ff1c4ca79feac551c0c7212a65e4091278ec886b88be01ee4039682238".upper()) 37 | base64.b16encode(pysodium.crypto_sign_detached(h.digest(), sk)).lower() 38 | 39 | lh = pyblake2.blake2b(digest_size=32) 40 | lh.update(bytearray([0x00])) 41 | lh.update(bytearray([0, 0, 0, 0, 0, 0, 0, 1])) 42 | hex(ord('a')) 43 | lh.update(bytearray([0x61])) 44 | lh.hexdigest() 45 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Free Software under GPL-3.0, see LICENSE 2 | // Copyright 2017 Bryan Newbold 3 | 4 | //! This is a hobby/learning implementation of the dat distributed data synchronization system. 5 | //! 6 | //! Subcomponents are roughly organized in library form for easier reading/review, but buyer-beware 7 | //! actually trying to reuse this code for anything other than education or interop testing. 8 | //! 9 | //! ### References 10 | //! 11 | //! [Dat Whitepaper](https://github.com/datproject/docs) 12 | //! 13 | //! Additional notes in the source code for this repo, under the 'notes' directory. Also, see 14 | //! README. 15 | 16 | extern crate crypto; 17 | extern crate env_logger; 18 | #[macro_use] 19 | extern crate error_chain; 20 | extern crate integer_encoding; 21 | #[macro_use] 22 | extern crate log; 23 | extern crate protobuf; 24 | extern crate rand; 25 | extern crate sodiumoxide; 26 | extern crate bit_field; 27 | extern crate resolve; 28 | extern crate data_encoding; 29 | #[macro_use] 30 | extern crate chan; 31 | extern crate bit_vec; 32 | 33 | #[cfg(test)] 34 | extern crate tempdir; 35 | 36 | #[allow(unused_doc_comments)] 37 | mod errors { 38 | 39 | // Create the Error, ErrorKind, ResultExt, and Result types 40 | error_chain! { 41 | foreign_links { Fmt(::std::fmt::Error); 42 | Io(::std::io::Error) #[cfg(unix)]; 43 | AddrParseError(::std::net::AddrParseError); 44 | Protobuf(::protobuf::ProtobufError); } 45 | } 46 | } 47 | 48 | #[doc(hidden)] 49 | pub use errors::*; 50 | 51 | // Organize code internally (files, modules), but pull it all into a flat namespace to export. 52 | mod helpers; 53 | pub use helpers::*; 54 | mod bitfield; 55 | pub use bitfield::*; 56 | mod sleep_file; 57 | pub use sleep_file::*; 58 | mod sleep_register; 59 | pub use sleep_register::*; 60 | mod drive; 61 | pub use drive::*; 62 | mod protocol; 63 | pub use protocol::*; 64 | pub mod network_msgs; 65 | pub mod metadata_msgs; 66 | mod discovery; 67 | pub use discovery::*; 68 | mod peer; 69 | pub use peer::*; 70 | mod synchronizer; 71 | pub use synchronizer::*; 72 | 73 | -------------------------------------------------------------------------------- /src/helpers.rs: -------------------------------------------------------------------------------- 1 | 2 | use errors::*; 3 | use crypto::digest::Digest; 4 | use crypto::blake2b::Blake2b; 5 | 6 | /// Helper to calculate a discovery key from a public key. 'key' should be 32 bytes; the returned 7 | /// array will also be 32 bytes long. 8 | /// 9 | /// dat discovery keys are calculated as a BLAKE2b "keyed hash" (using the passed key) of the string 10 | /// "hypercore" (with no trailing null byte). 11 | pub fn make_discovery_key(key: &[u8]) -> Vec { 12 | let mut discovery_key = [0; 32]; 13 | let mut hash = Blake2b::new_keyed(32, key); 14 | hash.input(&"hypercore".as_bytes()); 15 | hash.result(&mut discovery_key); 16 | discovery_key.to_vec() 17 | } 18 | 19 | /// Helper to parse a dat address (aka, public key) in string format. 20 | /// 21 | /// Address can start with 'dat://'. It should contain 64 hexadecimal characters. 22 | pub fn parse_dat_address(input: &str) -> Result> { 23 | 24 | let raw_key = if input.starts_with("dat://") { 25 | &input[6..] 26 | } else { 27 | input 28 | }; 29 | if raw_key.len() != 32 * 2 { 30 | bail!("dat key not correct length"); 31 | } 32 | let mut key_bytes = vec![]; 33 | for i in 0..32 { 34 | let r = u8::from_str_radix(&raw_key[2 * i..2 * i + 2], 16); 35 | match r { 36 | Ok(b) => key_bytes.push(b), 37 | Err(e) => bail!("Problem with hex: {}", e), 38 | }; 39 | } 40 | Ok(key_bytes) 41 | } 42 | 43 | #[test] 44 | fn test_parse_dat_address() { 45 | 46 | assert!(parse_dat_address( 47 | "c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok()); 48 | assert!(parse_dat_address( 49 | "C7638882870ABD4044D6467B0738F15E3A36F57C3A7F7F3417FD7E4E0841D597").is_ok()); 50 | assert!(parse_dat_address( 51 | "dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok()); 52 | 53 | assert!(parse_dat_address( 54 | "c7638882870ab").is_err()); 55 | assert!(parse_dat_address( 56 | "g7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_err()); 57 | assert!(parse_dat_address( 58 | "dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d5970").is_err()); 59 | assert!(parse_dat_address( 60 | "dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d59").is_err()); 61 | } 62 | -------------------------------------------------------------------------------- /notes/architecture.md: -------------------------------------------------------------------------------- 1 | 2 | peers wrap connections with given clients (any transport type). each peer can 3 | be talking about multiple feeds. state consists of which feeds, what the remote 4 | has (feed, bitmap), and what chunks (feed, index) have been requested 5 | ("in-flight"). connection logic runs in threads, passes back and forth entire 6 | messages in channels. 7 | 8 | ConnCommand 9 | Send(DatNetMessage) 10 | Terminate() 11 | 12 | ConnReply 13 | Received(DatNetMessage) 14 | Disconnected() 15 | 16 | A synchronizer event loop has local feeds (storage) and a bunch of peers. Extra 17 | state includes mode configuration, feeds, "wanted" bitmap for each feed. 18 | Callbacks for certain feed events allow for extension (eg, hyperdrive stuff). 19 | Needs a timer event. 20 | 21 | Use chan and chan-signal for now (MPSC style)... tokio will be the future but 22 | seems too unstable for now. mio is too low-level to use on it's own (eg, no 23 | timers, no threads). Use two threads per peer: a "main" thread that does 24 | connection setup, `chan_select`, and blocking writes, and a "reader" thread 25 | that does blocking reads of entire messages (writing either into the main 26 | thread or skipping straight to the output channel). Got this pattern from the 27 | `rusty_torrent` package. Need to set some write timeout. Synchronizer handles 28 | cleanup if peer isn't replying/heartbeating. 29 | 30 | Probably want a dedicated discovery thread/worker in the future, but for now 31 | just do it synchronously and connect to up to N peers to start. 32 | 33 | Synchronize will select on: 34 | 35 | signal 36 | graceful shutdown 37 | unified_inbound 38 | feed: depends on state; ignore for now 39 | handshake: error, close connection? 40 | have, info: update PeerState bitmap 41 | unhave, info, want, unwant: ignore for now 42 | request: depends on state; read from storage 43 | cancel: ignore for now 44 | data: write to storage, clear pending; send new request 45 | tick 46 | check peer states, kill if too slow 47 | dump status to command line 48 | 49 | Synchronize needs state: 50 | - "tried" peers, so we don't retry in a loop if they fail 51 | 52 | Synchronize options: 53 | - whether or not to hook signals 54 | 55 | Where does drive logic live? Plugin, via callback, to Synchronize? Let's just 56 | fold it in to synchronizer for now, as a mode flag. 57 | -------------------------------------------------------------------------------- /src/network_msgs.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto2"; 2 | 3 | // File copied from: https://github.com/mafintosh/hypercore-protocol/blob/master/schema.proto 4 | // Copyright (c) 2016 Mathias Buus 5 | // MIT License (MIT) 6 | 7 | // wire format is (
) 8 | // header is a varint, channel << 4 | <4-bit-type> 9 | 10 | // type=0, should be the first message sent on a channel 11 | message Feed { 12 | required bytes discoveryKey = 1; 13 | optional bytes nonce = 2; 14 | } 15 | 16 | // type=1, overall connection handshake. should be send just after the feed message on the first channel only 17 | message Handshake { 18 | optional bytes id = 1; 19 | optional bool live = 2; // keep the connection open forever? both ends have to agree 20 | optional bytes userData = 3; 21 | repeated string extensions = 4; 22 | } 23 | 24 | // type=2, message indicating state changes etc. 25 | // initial state for uploading/downloading is true 26 | // if both ends are not downloading and not live it is safe to consider the stream ended 27 | message Info { 28 | optional bool uploading = 1; 29 | optional bool downloading = 2; 30 | } 31 | 32 | // type=3, what do we have? 33 | message Have { 34 | required uint64 start = 1; 35 | optional uint64 length = 2 [default = 1]; // defaults to 1 36 | optional bytes bitfield = 3; 37 | } 38 | 39 | // type=4, what did we lose? 40 | message Unhave { 41 | required uint64 start = 1; 42 | optional uint64 length = 2 [default = 1]; // defaults to 1 43 | } 44 | 45 | // type=5, what do we want? remote should start sending have messages in this range 46 | message Want { 47 | required uint64 start = 1; 48 | optional uint64 length = 2; // defaults to Infinity or feed.length (if not live) 49 | } 50 | 51 | // type=6, what don't we want anymore? 52 | message Unwant { 53 | required uint64 start = 1; 54 | optional uint64 length = 2; // defaults to Infinity or feed.length (if not live) 55 | } 56 | 57 | // type=7, ask for data 58 | message Request { 59 | required uint64 index = 1; 60 | optional uint64 bytes = 2; 61 | optional bool hash = 3; 62 | optional uint64 nodes = 4; 63 | } 64 | 65 | // type=8, cancel a request 66 | message Cancel { 67 | required uint64 index = 1; 68 | optional uint64 bytes = 2; 69 | optional bool hash = 3; 70 | } 71 | 72 | // type=9, get some data 73 | message Data { 74 | message Node { 75 | required uint64 index = 1; 76 | required bytes hash = 2; 77 | required uint64 size = 3; 78 | } 79 | 80 | required uint64 index = 1; 81 | optional bytes value = 2; 82 | repeated Node nodes = 3; 83 | optional bytes signature = 4; 84 | } 85 | 86 | // type=15 (last massage) is an extension message 87 | // that is encoded like this 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | _ 3 | __ _ ___ _ __ (_)______ _ 4 | / _` |/ _ \ '_ \| |_ / _` | 5 | | (_| | __/ | | | |/ / (_| | 6 | \__, |\___|_| |_|_/___\__,_| 7 | |___/ 8 | 9 | 10 | this is a poor / partial / non-compliant dat implementation in rust. 11 | 12 | it will eat-your-data! 13 | 14 | ### Status 15 | 16 | [![Build Status](https://travis-ci.org/bnewbold/geniza.svg?branch=master)](https://travis-ci.org/bnewbold/geniza) 17 | 18 | - [ ] SLEEP v2 files and registers 19 | - [x] read/write file headers 20 | - [x] read/write file chunks as raw bytes 21 | - [x] pread/pwrite file chunks without seeking 22 | - [x] read data entries by index 23 | - [x] append data entries 24 | - [x] verify entire register (signatures and merkel tree) 25 | - [ ] receive and insert data out of order 26 | - [ ] bitfields 27 | - [ ] Drive metadata and files 28 | - [x] read full history ("log") 29 | - [x] read file tree ("ls") 30 | - [x] import file to register 31 | - [x] export file from register 32 | - [x] import/export directories recursively 33 | - [ ] Protocol 34 | - [x] send/receive encrypted messages to a known host 35 | - [ ] bitfields 36 | - [ ] Discovery 37 | - [x] centralized DNS 38 | - [ ] mDNS (local DNS) 39 | - [ ] DHT (distributed hash table) 40 | - [ ] Peer Synchronization 41 | - [ ] receive entire register from a known host 42 | - [ ] share (upload) register to a known host 43 | - [ ] Wrapper commands 44 | - [ ] clone 45 | - [ ] share 46 | - [x] log 47 | - [ ] status 48 | - [ ] add 49 | 50 | ### Differences from dat 51 | 52 | Significant simplifications were made compared to the regular dat client: 53 | 54 | - Content data is always stored in the SLEEP directory (`content.data`), 55 | instead of just having the latest data in files in the working directory. 56 | This results in data duplication. 57 | - Sparse registers aren't implemented: full history needs to be present for 58 | both metadata and content. 59 | - Tracking of remote node state (bitfields) is minimized as much as possible. 60 | - Almost everything is synchronous and single-threaded, so only a single remote 61 | node connection at a time is allowed. 62 | 63 | ### Dependencies 64 | 65 | Notable Rust Libraries: 66 | - `rust-crypto` for hashing (BLAKE2b) 67 | - `sodiumoxide` signing (Ed25519) and network stream encryption (XSalsa20) 68 | - `integer-encoding` for simple "varints" 69 | - `rust-protobuf` for protobuf messages 70 | 71 | Requires the libsodium library installed system-wide to run, and header files 72 | (`libsodium-dev`) for now, due to dynamic linking and the simple build 73 | configuration. It should be possible to statically link a free-standing 74 | executable, and to auto-build the libsodium C library during compilation if it 75 | isn't found system-wide. 76 | 77 | protobuf encode/decode methods are auto-generated ahead of time using 78 | `rust-protobuf`, so if you're just compiling or installing `geniza` you don't 79 | need any special tools. However, if you change or extend the `.proto` schema 80 | files, you do, along with the `protoc` tool (`sudo apt install 81 | protobuf-compiler`) and rust plugin `protoc-gen-rust` (`cargo install 82 | protobuf`). The command to regenerate a single file is: 83 | 84 | protoc --rust_out . network_msgs.proto 85 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | 2 | next: 3 | - "insert" for hypercore (also sparseness) 4 | - proper logging 5 | - Synchronizer 6 | => chan-signal to shutdown 7 | => "wanted" bitmap 8 | => design statemachine (global and per-peer) 9 | => actions for each message type 10 | => when a peer is ready, find a mutal chunk option, mark as in progress 11 | => some logic to do drive stuff (add new registers, etc) 12 | => probably an options builder? 13 | => accepting inbound connections 14 | - get everything to compile 15 | - clean up node bitfield implementation 16 | => use bit_vec (bit-vec = "0.4.4") instead of bit_field (remove) 17 | - "insert" API for HyperRegister (when we have a signed Data message) 18 | - how to create a Data message in response to a Request 19 | - sparse register clone 20 | - 'geniza clone' command 21 | - 'geniza checkout' command 22 | - 'geniza init', 'geniza commit' commands 23 | 24 | 25 | specific tests: 26 | - drive children array: deep directory nesting (like 'tree' example) 27 | - sleep info a variety of bad sleep files, should error 28 | - sleep create a known file, should be same as empty (also a "Rot13" algo file) 29 | - create a register, binary compare against known-good 30 | - test vectors of leaf, parent, and root hashes 31 | - test vectors of signatures 32 | - cloning with metadata pointing to relative or absolute paths 33 | ("dir/../../../../etc/passwd") 34 | 35 | performance: 36 | - cache SLEEP file length when opened (don't fstat all the time) 37 | - keep an LRU cache of SLEEP reads 38 | 39 | Backburner: 40 | - try switching to Coded{Input/Output}Stream for fewer copies/allocations 41 | - API to link and run from, eg, python 42 | - uTP transport 43 | - in-memory storage backend 44 | - compile to WASM... play in browser? 45 | - multi-connection network sync (per-connection state, etc) 46 | - duplicate file/chunk optimizations 47 | - secret_key-in-home helpers (read/write) 48 | - SLEEP bitfields stuff 49 | - .latest and .ogd files 50 | - benchmarks! syscall counts (strace), timing, etc 51 | - test fault injection... with strace? 52 | - consider kafka (append performance) and sqlite (robustness) file I/O patterns 53 | - manpage 54 | - slog for logging 55 | - disable sodiumoxide serde feature (faster/smaller build) 56 | - sodiumoxide static link 57 | https://safenetforum.org/t/building-a-non-dynamically-linked-executable-of-safe-vault/9811/6 58 | - SLEEP API: should just be empty string for algo-name, not Option<> 59 | - I have the SLEEP/register naming wrong... sleep refers to the directory? 60 | - portable positional file I/O 61 | https://github.com/vasi/positioned-io 62 | - mmap 63 | https://docs.rs/scroll/0.7.0/scroll/ 64 | - switch to byteorder for endian reads/writes 65 | - --json args to most CLI commands 66 | - ruthlessly simplify APIs 67 | - SleepFile from existing File (api) 68 | - refactor key generation into generic/re-usable function 69 | - turn magic numbers in tree nodes into declared (public?) constants 70 | - root_nodes as an iterator? (vs returning a Vec) 71 | - pretty terminal output: https://crates.io/crates/colored 72 | - error handling best practices: 73 | https://rust-lang-nursery.github.io/rust-cookbook/basics.html#obtain-backtrace-of-complex-error-scenarios 74 | - debug commands with hex i/o: 75 | https://github.com/ia0/data-encoding 76 | - sendfile() or splice() for disk-to-disk copying? 77 | - Rust FS API example: https://docs.rs/zbox/0.1.3/zbox/ 78 | - "bytes" crate 79 | -------------------------------------------------------------------------------- /notes/dat-spec-thoughts.md: -------------------------------------------------------------------------------- 1 | 2 | Edited and posted to: https://gist.github.com/bnewbold/c9cebbb9384236e3910fb9d4948cb054 3 | 4 | I've been implementing a dat client in Rust: https://github.com/bnewbold/geniza 5 | 6 | It's been fun! The "whitepaper"/spec has been very helpful. Below are a few thoughts/comments on the paper, documentation, and protocols. 7 | 8 | ## Informal Protocol Proposals 9 | 10 | With my archival and inter-op hat on, I wish that the hyperdrive metadata register (specifically Node protobuf messages) included standard full-file hashes (eg, SHA1 or BLAKE2b of the entire file, with no length prefix). These could be optional, but could presumably be calculated when adding files to archives with little overhead. This could make auditing, verification, and interoperability between distributed networks easier. Storage and compute overhead would be non-zero. 11 | 12 | It seems like the network protocol really should have a version field... in the initial pre-encryption Register message? 13 | 14 | I'm curious if the protobuf coded stream format (CodedInputStream/CodedOutputStream) was considered as an alternative to the existing {varint-length, varint-header, message} scheme. My brief reading of the coded streams is that they add varint length and type encoding to a stream of messages, which is almost exactly what the existing protocol is, but has broad support in well-optimized cross-platform wrapper libraries. The protocol network message scheme might need to change to have a wrapper type that wraps every message. This would be a clear place to include the channel identifier as a separate varint... which would add at least one byte overhead to each message. 15 | 16 | It might be nice to include an "added" timestamp to hyperdrive Node entries. The semantics would be the same as git commit messages: the timestamps are not verified or used in the protocol in any way, but are trusted in the same way the content itself is trusted (signed by creator) and is helpful for humans to understand what is going on. Commiter name (and email) could also be added, but that seems like a bigger can of worms than a simple UTC timestamp. 17 | 18 | ## Things I Learned 19 | 20 | I initially explored dat and read the paper over the summer. While implementing more recently I learned (or remembered) a few things. 21 | 22 | Appending to SLEEP registers ("append only logs") results in writes into middle of tree files (for root nodes). So, while the register as a whole is append-only, the files are not. This is obviously the case for sparse (or partial) synchronization, but is also the case for simple appends. From a disk I/O and caching standpoint, this seems suboptimal, in the context of being able to write dat tree files as fast as disk I/O allows. On reflection, it probably isn't that big of a dea.: clients can still operate on power-of-2 bulk chunks, and only need to backwards-write something like log(n) entries. My feelings on this are mostly speculative; "benchmarks needed". 23 | 24 | hypercore relies on libsodium for most cryptography, which seems like a wise decision. The details were not specified in the whitepaper (they should be!), but were easy to figure out: "XOR streaming" mode with XSalsa20 keys/nonces (defaults with libsodium for this use case). However, the use of the "streaming xor" API in the network protocol is somewhat non-standard: it does not seem to be supported or mentioned in the underlying (and well audited) NaCL code. This isn't hugely problematic, but it could be a roadbump for implementors in non-node.js languages. The particular necessary function which is not always included in language wrappers (and is not mentioned in libsodium documentation) is `crypto_stream_salsa20_xor_ic()`, which allows specifying a block offset when encrypting a buffer. 25 | 26 | My gut feeling is that protocol (network) messages should be prefixed with a fixed size uint32 instead of a varint... maybe i'm just old-fashioned though. As noted above, being compatible with coded/tagged streams of messages is probably best, and that scheme itself uses varints to encode length. 27 | 28 | ## A whole bunch of little notes 29 | 30 | - merkle tree: what if there is only a single chunk/entry in a register tree? then a leaf acts as a root? 31 | - unclear where protobuf schema actually lives... spread across multiple repos 32 | - protocol extension stuff not in the whitepaper 33 | - whitepaper should be versioned/tagged, or marked as "work in progress" 34 | - encryption not really covered in whitepaper... seems to be libsodium's XSalsa20 XOR'd with data 35 | - "ping" mechanism: sending a 1-byte message (0 length body) to keep channel alive 36 | 37 | ## Questions in the form of issues 38 | 39 | * [Please clarify key names and new SLEEP file types](https://github.com/datproject/docs/issues/93) 40 | * [Current chunking: content-aware? de-duped?](https://github.com/datproject/discussions/issues/77) 41 | * [Please clarify hyperdrive metadata "children"/"trie" encoding](https://github.com/datproject/docs/issues/92) 42 | * [Spec: how to delete files?](https://github.com/datproject/docs/issues/94) 43 | -------------------------------------------------------------------------------- /src/bin/geniza-net.rs: -------------------------------------------------------------------------------- 1 | // Free Software under GPL-3.0, see LICENSE 2 | // Copyright 2017 Bryan Newbold 3 | 4 | extern crate clap; 5 | extern crate env_logger; 6 | #[macro_use] 7 | extern crate error_chain; 8 | extern crate geniza; 9 | extern crate sodiumoxide; 10 | 11 | // TODO: more careful import 12 | use geniza::*; 13 | use std::path::Path; 14 | use clap::{App, SubCommand, Arg}; 15 | use sodiumoxide::crypto::stream::Key; 16 | 17 | fn run() -> Result<()> { 18 | env_logger::init().unwrap(); 19 | 20 | let matches = App::new("geniza-net") 21 | .version(env!("CARGO_PKG_VERSION")) 22 | .subcommand( 23 | SubCommand::with_name("connect") 24 | .about("Connects to a peer and exchanges handshake") 25 | .arg_from_usage(" 'peer host:port to connect to'") 26 | .arg_from_usage(" 'dat key (public key) to register with'"), 27 | ) 28 | .subcommand( 29 | SubCommand::with_name("discovery-key") 30 | .about("Prints (in hex) the discovery key for a dat archive") 31 | .arg_from_usage(" 'dat key (public key) to convert (in hex)'"), 32 | ) 33 | .subcommand( 34 | SubCommand::with_name("discovery-dns-name") 35 | .about("Prints the DNS name to query (mDNS or centrally) for peers") 36 | .arg_from_usage(" 'dat key (public key) to convert (in hex)'"), 37 | ) 38 | .subcommand( 39 | SubCommand::with_name("discover-dns") 40 | .about("Does a centralized DNS lookup for peers with the given key") 41 | .arg_from_usage(" 'dat key (public key) to lookup"), 42 | ) 43 | .subcommand( 44 | SubCommand::with_name("naive-clone") 45 | .about("Pulls a drive from a single (known) peer, using a naive algorithm") 46 | .arg(Arg::with_name("dat-dir") 47 | .short("d") 48 | .long("dat-dir") 49 | .value_name("PATH") 50 | .help("dat drive directory") 51 | .default_value(".dat") 52 | .takes_value(true)) 53 | .arg_from_usage(" 'peer host:port to connect to'") 54 | .arg_from_usage(" 'dat key (public key) to pull"), 55 | ) 56 | .get_matches(); 57 | 58 | 59 | match matches.subcommand() { 60 | ("connect", Some(subm)) => { 61 | let host_port = subm.value_of("host_port").unwrap(); 62 | let dat_key = subm.value_of("dat_key").unwrap(); 63 | let key_bytes = parse_dat_address(&dat_key)?; 64 | let key = Key::from_slice(&key_bytes).unwrap(); 65 | DatConnection::connect(host_port, &key, false, None)?; 66 | println!("Done!"); 67 | } 68 | ("discovery-key", Some(subm)) => { 69 | let dat_key = subm.value_of("dat_key").unwrap(); 70 | let key_bytes = parse_dat_address(&dat_key)?; 71 | let disc_key = make_discovery_key(&key_bytes); 72 | for b in disc_key { 73 | print!("{:02x}", b); 74 | } 75 | println!(""); 76 | } 77 | ("discovery-dns-name", Some(subm)) => { 78 | let dat_key = subm.value_of("dat_key").unwrap(); 79 | let key_bytes = parse_dat_address(&dat_key)?; 80 | let disc_key = make_discovery_key(&key_bytes); 81 | for b in 0..20 { 82 | print!("{:02x}", disc_key[b]); 83 | } 84 | println!(".dat.local"); 85 | } 86 | ("discover-dns", Some(subm)) => { 87 | let dat_key = subm.value_of("dat_key").unwrap(); 88 | let key_bytes = parse_dat_address(&dat_key)?; 89 | let peers = discover_peers_dns(&key_bytes)?; 90 | if peers.len() == 0 { 91 | println!("No peers found!"); 92 | } else { 93 | for p in peers { 94 | println!("{}", p); 95 | } 96 | } 97 | } 98 | ("naive-clone", Some(subm)) => { 99 | let host_port = subm.value_of("host_port").unwrap(); 100 | let dat_key = subm.value_of("dat_key").unwrap(); 101 | let key_bytes = parse_dat_address(&dat_key)?; 102 | let dir = Path::new(subm.value_of("dat-dir").unwrap()); 103 | let mut metadata = SleepDirRegister::create(&dir, "metadata")?; 104 | node_simple_clone(host_port, &key_bytes, &mut metadata, 0)?; 105 | // TODO: read out content key from metadata register 106 | //let content = SleepDirRegister::create(&dir, "content")?; 107 | //node_simple_clone(host_port, &key_bytes, &mut content, true)?; 108 | } 109 | _ => { 110 | println!("Missing or unimplemented command!"); 111 | println!("{}", matches.usage()); 112 | ::std::process::exit(-1); 113 | } 114 | } 115 | Ok(()) 116 | } 117 | 118 | quick_main!(run); 119 | -------------------------------------------------------------------------------- /src/peer.rs: -------------------------------------------------------------------------------- 1 | 2 | use errors::*; 3 | use std::thread; 4 | use std::net::ToSocketAddrs; 5 | use std::fmt::Display; 6 | use std::time::Duration; 7 | use protocol::{DatConnection, DatNetMessage}; 8 | use network_msgs::*; 9 | use sodiumoxide::crypto::stream::Key; 10 | use make_discovery_key; 11 | use chan; 12 | 13 | /// Wraps a low-level DatConnection in a thread (or two). Contains very little context about 14 | /// itself. 15 | pub struct DatPeerThread { 16 | pub handle: u64, 17 | feeds: Vec<(u8, Key)>, 18 | outbound_chan: chan::Sender<(DatNetMessage, u8)>, 19 | } 20 | 21 | pub struct PeerMsg { 22 | pub peer_handle: u64, 23 | pub feed_index: u8, 24 | pub msg: DatNetMessage, 25 | } 26 | 27 | /// This is what the "receive" loop does: simply blocking reads on the TCP socket, passing any 28 | /// received messages into a channel back to the worker thread. 29 | fn receiver_loop(mut dc: DatConnection, peer_rx: chan::Sender>) { 30 | loop { 31 | match dc.recv_msg() { 32 | Ok((msg, feed_index)) => { 33 | peer_rx.send(Ok((msg, feed_index))); 34 | }, 35 | Err(e) => { 36 | // XXX: check if this was due to socket closing cleanly, in which case don't pass 37 | // error along 38 | peer_rx.send(Err(e)); 39 | return 40 | }, 41 | } 42 | } 43 | } 44 | 45 | /// Worker thread. After initializing the connection, loops endlessly. Looks for outgoing PeerMsg 46 | /// on the command channel, and sends these directly (blocking). Also looks for raw received 47 | /// messages (via a spawned receiver thread), and enhances these with extra context then passes 48 | /// upwards on the unified peer message channel. 49 | fn worker_thread(mut dc: DatConnection, handle: u64, outbound_chan: chan::Receiver<(DatNetMessage, u8)>, unified_chan: chan::Sender>) { 50 | 51 | dc.tcp.set_write_timeout(Some(Duration::new(2, 0))).unwrap(); 52 | 53 | let rx_dc = dc.clone(); 54 | let (receiver_chan, raw_peer_rx) = chan::async(); 55 | thread::spawn(move || { 56 | receiver_loop(rx_dc, receiver_chan); 57 | }); 58 | 59 | loop { 60 | chan_select!{ 61 | outbound_chan.recv() -> val => { 62 | if let Some((msg, feed_index)) = val { 63 | match dc.send_msg(&msg, feed_index) { 64 | Ok(_) => {}, 65 | Err(e) => { 66 | // TODO: error chain! 67 | unified_chan.send(Err(e)); 68 | return 69 | } 70 | } 71 | }; 72 | }, 73 | raw_peer_rx.recv() -> val => { 74 | match val { 75 | Some(Ok((msg, feed_index))) => { 76 | // do mapping between feed index and feed pubkey here 77 | let pm = PeerMsg { 78 | peer_handle: handle, 79 | feed_index: feed_index, 80 | msg, 81 | }; 82 | unified_chan.send(Ok(pm)); 83 | }, 84 | Some(Err(err)) => { 85 | println!("remote socket error: {:?}", err); 86 | // XXX: Need to send something so we know to close 87 | unified_chan.send(Err(err)); 88 | dc.close(); 89 | return; 90 | }, 91 | None => { 92 | println!("remote socket closed"); 93 | // XXX: Need to send something so we know to close 94 | //unified_chan.send(Err(err)); 95 | dc.close(); 96 | return; 97 | } 98 | }; 99 | } 100 | }; 101 | } 102 | } 103 | 104 | impl DatPeerThread { 105 | 106 | pub fn connect(addr: A, feed_key: Key, handle: u64, is_live: bool, local_id: Option<&[u8]>, unified_chan: chan::Sender>) -> Result { 107 | 108 | let addr = addr.to_socket_addrs().unwrap().nth(0).unwrap(); 109 | let (outbound_chan, tx_chan) = chan::async(); 110 | let feed_key2 = feed_key.clone(); 111 | 112 | // Do an ugly little dance to copy local_id across thread barrier 113 | let mut id_buf = [0; 32]; 114 | let local_id = match local_id { 115 | None => None, 116 | Some(val) => { 117 | id_buf.copy_from_slice(val); 118 | Some(id_buf) 119 | }, 120 | }; 121 | thread::spawn(move || { 122 | 123 | let local_id = match local_id { 124 | None => None, 125 | Some(_val) => { 126 | Some(&id_buf[..]) 127 | }, 128 | }; 129 | let dc = match DatConnection::connect(addr, &feed_key, is_live, local_id) { 130 | Ok(c) => c, 131 | Err(e) => { 132 | // TODO: error chain! 133 | unified_chan.send(Err(e)); 134 | return; 135 | }, 136 | }; 137 | 138 | worker_thread(dc, handle, tx_chan, unified_chan); 139 | }); 140 | 141 | let dp = DatPeerThread { 142 | handle, 143 | outbound_chan, 144 | feeds: vec![(0, feed_key2)], 145 | }; 146 | Ok(dp) 147 | } 148 | 149 | pub fn send(&mut self, net_msg: DatNetMessage, feed_index: u8) -> Result<()> { 150 | self.outbound_chan.send((net_msg, feed_index)); 151 | Ok(()) 152 | } 153 | 154 | pub fn add_feed(&mut self, key: &Key) -> Result<()> { 155 | 156 | let key_bytes = &key[0..32]; 157 | let key = Key::from_slice(key_bytes).unwrap(); 158 | 159 | for k in self.feeds.iter() { 160 | if (*k).1 == key { 161 | warn!("tried to add existing feed/key on a DatPeerThread connection"); 162 | return Ok(()) 163 | } 164 | } 165 | 166 | let index = self.feeds.len(); 167 | assert!(index < 256); 168 | let discovery_key = make_discovery_key(key_bytes);; 169 | 170 | // Send (encrypted) Feed message for data feed 171 | let mut feed_msg = Feed::new(); 172 | feed_msg.set_discoveryKey(discovery_key.to_vec()); 173 | self.outbound_chan.send((DatNetMessage::Feed(feed_msg), index as u8)); 174 | 175 | self.feeds.push((index as u8, key.clone())); 176 | Ok(()) 177 | } 178 | 179 | pub fn close(&mut self) -> Result<()> { 180 | unimplemented!(); 181 | } 182 | } 183 | 184 | -------------------------------------------------------------------------------- /notes/crypto/notes.txt: -------------------------------------------------------------------------------- 1 | 2 | libsodium Ed25519 keys, Blake2b 32-bit hashes 3 | 4 | This file is a WIP. The 'simple' example might have errors; the hypercore tests 5 | and 'alphabet' example seemed to actually work (aka, matches dat upstream 6 | client behavior). 7 | 8 | ====== simple 9 | 10 | bnewbold@orithena$ cat test-data/dat/simple/.dat/content.key | base64 11 | BnlFLuVBAS6rYID8wUCmIS/O85v/jJ9i7ousH16C0r0= 12 | 13 | 14 | metadata pub: 15 | len_bytes: 32 16 | hex: cb1e8d65f3c6242db90bfd99accaf47930ea3ff6c852fb50caaa548c9cdcb8b7 17 | base64: yx6NZfPGJC25C/2ZrMr0eTDqP/bIUvtQyqpUjJzcuLc= 18 | 19 | metadata secret: 20 | len_bytes: 64 21 | file: ~/.dat/secret_keys/bf/feaefe7cb34458e11ecb1e38b67b5f93eafce2bd7a286db229a87f0384e61c 22 | hex: ab3bd2909310796c36ac66f85bec5b18d4e09397449225623adab99e23a41224cb1e8d65f3c6242db90bfd99accaf47930ea3ff6c852fb50caaa548c9cdcb8b7 23 | base64: qzvSkJMQeWw2rGb4W+xbGNTgk5dEkiViOtq5niOkEiTLHo1l88YkLbkL/ZmsyvR5MOo/9shS+1DKqlSMnNy4tw== 24 | 25 | discovery key: 26 | len_bytes: 32 27 | hex: bffeaefe7cb34458e11ecb1e38b67b5f93eafce2bd7a286db229a87f0384e61c 28 | 29 | content pub: 30 | len_bytes: 32 31 | hex: 0679452ee541012eab6080fcc140a6212fcef39bff8c9f62ee8bac1f5e82d2bd 32 | base64: BnlFLuVBAS6rYID8wUCmIS/O85v/jJ9i7ousH16C0r0= 33 | 34 | content secret: 35 | len_bytes: 64 36 | hex: c322b4918b90e53f13ab14c7e86dec7e5e7bd4128b585dac6bdf0353f8e4974f0679452ee541012eab6080fcc140a6212fcef39bff8c9f62ee8bac1f5e82d2bd 37 | base64: wyK0kYuQ5T8TqxTH6G3sfl571BKLWF2sa98DU/jkl08GeUUu5UEBLqtggPzBQKYhL87zm/+Mn2Lui6wfXoLSvQ== 38 | 39 | To make a discovery key, do a "keyed" Blake2b hash of the string "hypercore" (9 40 | bytes, no null) using the public key. 41 | 42 | bnewbold@orithena$ ./target/debug/geniza-sleep file-read-all test-data/dat/simple/.dat/content.tree 43 | 0: 44 | debug: Ok([103, 23, 156, 36, 59, 56, 123, 124, 124, 66, 11, 215, 189, 198, 157, 53, 192, 97, 185, 121, 187, 54, 95, 156, 192, 123, 69, 39, 238, 221, 238, 250, 0, 0, 0, 0, 0, 0, 0, 66]) 45 | hex: 67179c243b387b7c7c420bd7bdc69d35c061b979bb365f9cc07b4527eeddeefa0000000000000042 46 | 1: 47 | debug: Ok([43, 235, 230, 134, 54, 24, 197, 134, 8, 109, 37, 32, 170, 13, 19, 218, 102, 107, 0, 46, 90, 210, 177, 98, 35, 161, 91, 193, 85, 134, 241, 228, 0, 0, 0, 0, 0, 0, 0, 204]) 48 | hex: 2bebe6863618c586086d2520aa0d13da666b002e5ad2b16223a15bc15586f1e400000000000000cc 49 | 2: 50 | debug: Ok([163, 78, 52, 182, 129, 66, 214, 34, 130, 211, 196, 230, 152, 173, 250, 133, 82, 164, 113, 127, 75, 106, 60, 76, 179, 136, 210, 137, 113, 45, 233, 250, 0, 0, 0, 0, 0, 0, 0, 138]) 51 | hex: a34e34b68142d62282d3c4e698adfa8552a4717f4b6a3c4cb388d289712de9fa000000000000008a 52 | 53 | Signature file should be 64 byte each: 54 | 55 | bnewbold@orithena$ ./target/debug/geniza-sleep file-read-all test-data/dat/simple/.dat/content.signatures 56 | 0: 57 | debug: Ok([235, 70, 69, 206, 179, 128, 50, 76, 255, 139, 94, 124, 133, 55, 170, 130, 46, 139, 101, 250, 234, 52, 122, 184, 195, 40, 149, 95, 215, 220, 160, 39, 99, 173, 22, 146, 226, 165, 213, 245, 57, 186, 81, 45, 159, 218, 248, 109, 140, 172, 99, 57, 155, 180, 128, 17, 181, 220, 90, 22, 238, 78, 81, 1]) 58 | hex: eb4645ceb380324cff8b5e7c8537aa822e8b65faea347ab8c328955fd7dca02763ad1692e2a5d5f539ba512d9fdaf86d8cac63399bb48011b5dc5a16ee4e5101 59 | 1: 60 | debug: Ok([53, 69, 157, 171, 205, 82, 230, 197, 158, 124, 63, 2, 46, 165, 192, 24, 86, 33, 58, 126, 220, 80, 116, 202, 6, 194, 40, 108, 160, 63, 63, 245, 248, 171, 2, 76, 207, 153, 236, 176, 192, 193, 17, 45, 64, 246, 160, 228, 9, 120, 117, 115, 209, 34, 91, 117, 210, 82, 15, 238, 21, 160, 151, 9]) 61 | hex: 35459dabcd52e6c59e7c3f022ea5c01856213a7edc5074ca06c2286ca03f3ff5f8ab024ccf99ecb0c0c1112d40f6a0e409787573d1225b75d2520fee15a09709 62 | 63 | 64 | Paper says: 65 | 66 | Ed25519 sign( 67 | BLAKE2b( 68 | <1 byte> 2 // root type 69 | for (every root node left-to-right) { 70 | <32 byte root hash> 71 | <8 byte Uint64BE root tree index> 72 | <8 byte Uint64BE child byte lengths> 73 | } 74 | ) 75 | ) 76 | 77 | =========== example from hypercore tests 78 | 79 | Data chunks are just 'a', 'b', 'c'. 80 | 81 | Public key: 82 | 9718a1ff1c4ca79feac551c0c7212a65e4091278ec886b88be01ee4039682238 83 | 84 | Secret key: 85 | 53729c0311846cca9cc0eded07aaf9e6689705b6a0b1bb8c3a2a839b72fda3839718a1ff1c4ca79feac551c0c7212a65e4091278ec886b88be01ee4039682238 86 | 87 | Tree: 88 | 0: ab27d45f509274ce0d08f4f09ba2d0e0d8df61a0c2a78932e81b5ef26ef398df0000000000000001 89 | 1: 064321a8413be8c604599689e2c7a59367b031b598bceeeb16556a8f3252e0de0000000000000002 90 | 2: 94c17054005942a002c7c39fbb9c6183518691fb401436f1a2f329b380230af80000000000000001 91 | 3: 00000000000000000000000000000000000000000000000000000000000000000000000000000000 92 | 4: 94c17054005942a002c7c39fbb9c6183518691fb401436f1a2f329b380230af80000000000000001 93 | 94 | BLAKE2b ( 95 | 00, 96 | 00 00 00 00 00 00 00 01, 97 | 61, 98 | ) = ab27d45f509274ce0d08f4f09ba2d0e0d8df61a0c2a78932e81b5ef26ef398df 99 | 100 | Signatures: 101 | 0: 84684e8dd76c339d6f5754e813204906ee818e6c6cdc6a816a2ac785a3e0d926ac08641a904013194fe6121847b7dad4e361965d47715428eb0a0ededbdd5909 102 | 1: d037ff3c3614fa0100ed9264a712d3b77cbe7a4f6eadd8f342809be99dfb9154a19e278d7a5de7d2b4d890f7701a38b006469f6bab1aff66ac6125d48bafdc07 103 | 2: 11057675ed57d445ce7ed4613881be37ebc56bb40556b822e431bb4dc3517421f9a5e3ed124eb5c4db8367386d9ce12b2408613b9fec2837022772a635ffd807 104 | 105 | 106 | Ed25519 sign( 107 | BLAKE2b ( 108 | 02, 109 | ab27d45f509274ce0d08f4f09ba2d0e0d8df61a0c2a78932e81b5ef26ef398df, 110 | 00 00 00 00 00 00 00 00, 111 | 00 00 00 00 00 00 00 01, 112 | ) = fd09e68350db613d3afc9390abf12a7c2693d602b69012ff068251568d05887b 113 | ) = 84684e8dd76c339d6f5754e813204906ee818e6c6cdc6a816a2ac785a3e0d926ac08641a904013194fe6121847b7dad4e361965d47715428eb0a0ededbdd5909 114 | 115 | Cool! It works! 116 | 117 | ====== alphabet 118 | 119 | Tree: 120 | 0: ab27d45f509274ce0d08f4f09ba2d0e0d8df61a0c2a78932e81b5ef26ef398df0000000000000001 121 | 1: 064321a8413be8c604599689e2c7a59367b031b598bceeeb16556a8f3252e0de0000000000000002 122 | 2: 94c17054005942a002c7c39fbb9c6183518691fb401436f1a2f329b380230af80000000000000001 123 | 124 | ab27d45f509274ce0d08f4f09ba2d0e0d8df61a0c2a78932e81b5ef26ef398df0000000000000001 125 | 588e663097be0b31a3862613f96a1826be03c4ee529f11a495d193465d42b4ab0000000000000002 <= AH HA! parent hashing 126 | 064321a8413be8c604599689e2c7a59367b031b598bceeeb16556a8f3252e0de0000000000000002 127 | 128 | Ah, the gotcha: when making parent hashes, make sure to only include child 129 | *hashes* (32-bytes), not entire child entries (40 bytes, including lengths). 130 | 131 | Ah, and signatures were failing because I was passing an index to 132 | tree_root_nodes(), not an entry_count (index+1). 133 | -------------------------------------------------------------------------------- /src/bin/geniza.rs: -------------------------------------------------------------------------------- 1 | // Free Software under GPL-3.0, see LICENSE 2 | // Copyright 2017 Bryan Newbold 3 | 4 | extern crate clap; 5 | extern crate env_logger; 6 | #[macro_use] 7 | extern crate error_chain; 8 | extern crate geniza; 9 | extern crate sodiumoxide; 10 | 11 | // TODO: more careful import 12 | use geniza::*; 13 | use std::path::{Path, PathBuf}; 14 | use clap::{App, SubCommand}; 15 | use std::env::current_dir; 16 | use sodiumoxide::crypto::stream::Key; 17 | 18 | 19 | // Helper to find a dat directory somewhere in the parent to the current working directory (or None 20 | // if not found) 21 | fn find_dat_dir() -> Option { 22 | let mut here: &Path = ¤t_dir().unwrap(); 23 | loop { 24 | let check = here.join(".dat"); 25 | if check.is_dir() && check.join("metadata.tree").is_file() { 26 | return Some(check); 27 | }; 28 | here = match here.parent() { 29 | None => return None, 30 | Some(t) => t, 31 | } 32 | } 33 | } 34 | 35 | fn run() -> Result<()> { 36 | env_logger::init().unwrap(); 37 | 38 | let matches = App::new("geniza") 39 | .version(env!("CARGO_PKG_VERSION")) 40 | .subcommand( 41 | SubCommand::with_name("clone") 42 | .about("Finds and downloads a dat archive from the network into a given folder") 43 | .arg_from_usage("
'dat address (public key) to fetch'") 44 | .arg_from_usage("[dir] 'directory to clone into'") 45 | .arg_from_usage("--full 'pull and save complete history (not just latest version)'"), 46 | ) 47 | .subcommand( 48 | SubCommand::with_name("init") 49 | .about("Creates a data archive in the current directory") 50 | .arg_from_usage("[dir] 'init somewhere other than current directory'"), 51 | ) 52 | .subcommand( 53 | SubCommand::with_name("status") 54 | .about("Displays current status of archive and checkout") 55 | ) 56 | .subcommand( 57 | SubCommand::with_name("log") 58 | .about("Displays version history of the archive") 59 | ) 60 | .subcommand( 61 | SubCommand::with_name("checkout") 62 | .about("Copies (or overwrites) files from dat archive") 63 | .arg_from_usage(" 'relative path to checkout'"), 64 | ) 65 | .subcommand( 66 | SubCommand::with_name("add") 67 | .about("Adds a path to the current dat archive") 68 | .arg_from_usage(" 'file to delete from dat archive'"), 69 | ) 70 | .subcommand( 71 | SubCommand::with_name("rm") 72 | .about("Removes a path from the current dat archive, and from disk (danger!)") 73 | .arg_from_usage(" 'file to delete from dat archive'"), 74 | ) 75 | .subcommand( 76 | SubCommand::with_name("ls") 77 | .about("Lists contents of the archive") 78 | .arg_from_usage("[path] 'path to display'") 79 | .arg_from_usage("--recursive 'show directory recursively'"), 80 | ) 81 | .subcommand( 82 | SubCommand::with_name("seed") 83 | .about("Uploads indefinately to any peer") 84 | ) 85 | .subcommand( 86 | SubCommand::with_name("pull") 87 | .about("Pulls highest known version from all possible peers") 88 | .arg_from_usage("--forever 'continues to search for updates forever'"), 89 | ) 90 | .get_matches(); 91 | 92 | match matches.subcommand() { 93 | ("clone", Some(subm)) => { 94 | let dat_key = subm.value_of("address").unwrap(); 95 | let key_bytes = parse_dat_address(&dat_key)?; 96 | let key = Key::from_slice(&key_bytes).unwrap(); 97 | let dir = Path::new(subm.value_of("dir").unwrap()); 98 | 99 | let mut sync = Synchronizer::new_downloader(key, 100 | SyncMode::RxMax, 101 | dir)?; 102 | let peer_count = sync.discover()?; 103 | println!("Found {} potential peers", peer_count); 104 | sync.run()?; 105 | } 106 | ("init", Some(subm)) => { 107 | let _dir = Path::new(subm.value_of("dir").unwrap()); 108 | unimplemented!(); 109 | } 110 | ("status", Some(_subm)) => { 111 | unimplemented!(); 112 | } 113 | ("log", Some(_subm)) => { 114 | let dat_dir = match find_dat_dir() { 115 | Some(p) => p, 116 | None => { 117 | println!("Couldn't find '.dat/' in the current or (any parent) directory."); 118 | println!("Are you running from inside a Dat archive?"); 119 | ::std::process::exit(-1); 120 | } 121 | }; 122 | println!("{:?}", dat_dir); 123 | let mut drive = DatDrive::open(dat_dir, false)?; 124 | for entry in drive.history(0) { 125 | let entry = entry?; 126 | if let Some(stat) = entry.stat { 127 | if stat.get_blocks() == 0 { 128 | println!("{}\t[chg] {}", 129 | entry.index, entry.path.display()); 130 | } else { 131 | println!("{}\t[put] {}\t{} bytes ({} blocks)", 132 | entry.index, entry.path.display(), stat.get_size(), stat.get_blocks()); 133 | } 134 | } else { 135 | println!("{}\t[del] {}", 136 | entry.index, entry.path.display()); 137 | } 138 | } 139 | } 140 | ("checkout", Some(subm)) => { 141 | let _path = Path::new(subm.value_of("path").unwrap()); 142 | unimplemented!(); 143 | } 144 | ("add", Some(subm)) => { 145 | let _path = Path::new(subm.value_of("path").unwrap()); 146 | unimplemented!(); 147 | } 148 | ("rm", Some(subm)) => { 149 | let _path = Path::new(subm.value_of("path").unwrap()); 150 | unimplemented!(); 151 | } 152 | ("ls", Some(subm)) => { 153 | let _path = Path::new(subm.value_of("path").unwrap()); 154 | unimplemented!(); 155 | } 156 | ("seed", Some(subm)) => { 157 | let _path = Path::new(subm.value_of("path").unwrap()); 158 | unimplemented!(); 159 | } 160 | ("pull", Some(subm)) => { 161 | let _path = Path::new(subm.value_of("path").unwrap()); 162 | unimplemented!(); 163 | } 164 | _ => { 165 | println!("Missing or unimplemented command!"); 166 | println!("{}", matches.usage()); 167 | ::std::process::exit(-1); 168 | } 169 | } 170 | Ok(()) 171 | } 172 | 173 | quick_main!(run); 174 | -------------------------------------------------------------------------------- /src/sleep_file.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::io::prelude::*; 3 | use std::os::unix::fs::FileExt; 4 | use std::path::Path; 5 | use std::fs::File; 6 | use integer_encoding::FixedInt; 7 | use std::fs::OpenOptions; 8 | 9 | use errors::*; 10 | 11 | /// Abstract access to SLEEP content 12 | /// 13 | /// Back-ends could be in RAM, on disk, remote HTTP, etc. 14 | pub trait SleepStorage { 15 | /// Returns the 32-bit "magic word", indicating the content type, in native format (aka, not 16 | /// necessarily big-endian). 17 | fn get_magic(&self) -> u32; 18 | 19 | /// If the algorithm string is empty, returns None, otherwise the String (owned), decoded from 20 | /// UTF-8. Encoded (bytes) representation is at most 24 bytes. 21 | fn get_algorithm(&self) -> Option; 22 | 23 | /// Size (in bytes) of each entry for this SLEEP file. 24 | fn get_entry_size(&self) -> u16; 25 | 26 | /// Returns a single raw entry at the given index (which is not a byte offset). 27 | /// TODO: should write into a supplied buffer and return size. 28 | fn read(&mut self, index: u64) -> Result>; 29 | 30 | /// Writes an entry at the given entry index (which is not a byte offset). 31 | fn write(&mut self, index: u64, data: &[u8]) -> Result<()>; 32 | 33 | /// Writes a new entry at the end of the file 34 | fn append(&mut self, data: &[u8]) -> Result<()>; 35 | 36 | /// Returns the count of entries, meaning the highest index entry plus one (not necessarily the 37 | /// number of entries which have actually been written). 38 | fn len(&self) -> Result; 39 | } 40 | 41 | /// Local File implementation of SleepStorage 42 | #[derive(Debug)] 43 | pub struct SleepFile { 44 | pub file: File, 45 | magic: u32, 46 | entry_size: u16, 47 | // Option isn't necessary here... idiomatic? 48 | algorithm_name: Option, 49 | } 50 | 51 | impl SleepFile { 52 | // TODO: 'from' pre-existing File 53 | 54 | // Something here to allow paths as references or actual Path... 55 | pub fn open(path: &Path, writable: bool) -> Result { 56 | let mut f = OpenOptions::new() 57 | .read(true) 58 | .write(writable) 59 | .create(false) 60 | .open(path)?; 61 | let mut header = [0; 32]; 62 | f.read_exact(&mut header)?; 63 | let version: u8 = header[4]; 64 | if version != 0 { 65 | bail!("Invalid SLEEP header: version must be 0"); 66 | } 67 | let algo_len: u8 = header[7]; 68 | if algo_len > 24 { 69 | bail!("Invalid SLEEP header: can't have algo_len > 24"); 70 | } 71 | let algorithm_name = if algo_len == 0 { 72 | None 73 | } else { 74 | Some(String::from_utf8_lossy(&header[8..(8 + (algo_len as usize))]).into_owned()) 75 | }; 76 | let sf = SleepFile { 77 | file: f, 78 | magic: u32::from_be(FixedInt::decode_fixed(&header[0..4])), 79 | entry_size: u16::from_be(FixedInt::decode_fixed(&header[5..7])), 80 | algorithm_name: algorithm_name, 81 | }; 82 | // call length for consistency checks 83 | sf.len()?; 84 | Ok(sf) 85 | } 86 | 87 | /// This function will *not* allow overwriting an existing file. 88 | pub fn create( 89 | path: &Path, 90 | magic: u32, 91 | entry_size: u16, 92 | algo: Option, 93 | ) -> Result { 94 | let mut header = [0; 32]; 95 | u32::to_be(magic).encode_fixed(&mut header[0..4]); 96 | header[4] = 0; // version 97 | u16::to_be(entry_size).encode_fixed(&mut header[5..7]); 98 | if let Some(name) = algo.clone() { 99 | let name = name.as_bytes(); 100 | let algo_len = name.len(); 101 | if algo_len > 24 { 102 | bail!("Algorithm name must be 24 bytes at most"); 103 | } 104 | header[7] = algo_len as u8; 105 | header[8..(8 + algo_len)].clone_from_slice(name); 106 | } else { 107 | header[7] = 0; 108 | }; 109 | 110 | let mut f = OpenOptions::new() 111 | .read(true) 112 | .write(true) 113 | .create_new(true) 114 | .open(path)?; 115 | f.write_all(&header)?; 116 | Ok(SleepFile { 117 | file: f, 118 | magic: magic, 119 | entry_size: entry_size, 120 | algorithm_name: algo, 121 | }) 122 | } 123 | } 124 | 125 | impl SleepStorage for SleepFile { 126 | fn get_magic(&self) -> u32 { 127 | self.magic 128 | } 129 | fn get_algorithm(&self) -> Option { 130 | self.algorithm_name.clone() 131 | } 132 | fn get_entry_size(&self) -> u16 { 133 | self.entry_size 134 | } 135 | 136 | fn read(&mut self, index: u64) -> Result> { 137 | let entry_size = self.entry_size as usize; 138 | if index + 1 > self.len()? { 139 | bail!("Tried to read beyond end of SLEEP file"); 140 | } 141 | let mut entry = vec![0; entry_size]; 142 | let got = self.file.read_at(&mut entry, 32 + (entry_size as u64) * index)?; 143 | if got != entry.len() { 144 | bail!("Short file read"); 145 | } 146 | Ok(entry) 147 | } 148 | 149 | fn write(&mut self, index: u64, data: &[u8]) -> Result<()> { 150 | // TODO: need to extend file seek beyond end? 151 | if data.len() != self.entry_size as usize { 152 | bail!("Tried to write mis-sized data"); 153 | } 154 | let put = self.file.write_at(&data, 32 + (self.entry_size as u64) * index)?; 155 | if put != data.len() { 156 | bail!("Short file write"); 157 | } 158 | Ok(()) 159 | } 160 | 161 | fn append(&mut self, data: &[u8]) -> Result<()> { 162 | let index = self.len()?; 163 | self.write(index, data) 164 | } 165 | 166 | fn len(&self) -> Result { 167 | let length = self.file.metadata()?.len(); 168 | if length < 32 || (length - 32) % (self.entry_size as u64) != 0 { 169 | bail!("Bad SLEEP file: missing header or not multiple of entry_size"); 170 | } 171 | return Ok((length - 32) / (self.entry_size as u64)); 172 | } 173 | } 174 | 175 | #[test] 176 | fn test_sleep_open() { 177 | let sf = SleepFile::open(Path::new("test-data/sleep/empty/empty.sleep"), false).unwrap(); 178 | 179 | assert_eq!(sf.len().unwrap(), 0); 180 | assert_eq!(sf.get_magic(), 0x050257FF); 181 | assert_eq!(sf.get_algorithm(), None); 182 | assert_eq!(sf.get_entry_size(), 1); 183 | 184 | let sf = SleepFile::open(Path::new("test-data/dat/simple/.dat/metadata.tree"), false).unwrap(); 185 | 186 | // Calculated from 'dat log' 187 | assert_eq!(sf.len().unwrap(), 5); 188 | assert_eq!(sf.get_magic(), 0x05025702); 189 | assert_eq!(sf.get_algorithm(), Some("BLAKE2b".to_string())); 190 | assert_eq!(sf.get_entry_size(), 40); 191 | } 192 | 193 | #[test] 194 | fn test_sleep_create() { 195 | use tempdir::TempDir; 196 | let tmp_dir = TempDir::new("geniza-test").unwrap(); 197 | 198 | SleepFile::create(&tmp_dir.path().join("empty2.sleep"), 0x050257FF, 1, None).unwrap(); 199 | 200 | // TODO: binary diff against 'test-data/sleep/empty/empty.sleep' 201 | 202 | SleepFile::create( 203 | &tmp_dir.path().join("simple_metadata.sleep"), 204 | 0x05025702, 205 | 40, 206 | Some("BLAKE2b".into()), 207 | ).unwrap(); 208 | } 209 | -------------------------------------------------------------------------------- /src/bin/geniza-sleep.rs: -------------------------------------------------------------------------------- 1 | // Free Software under GPL-3.0, see LICENSE 2 | // Copyright 2017 Bryan Newbold 3 | 4 | #[macro_use] 5 | extern crate clap; 6 | extern crate env_logger; 7 | #[macro_use] 8 | extern crate error_chain; 9 | extern crate geniza; 10 | 11 | // TODO: more careful import 12 | use geniza::*; 13 | use std::path::Path; 14 | use clap::{App, SubCommand}; 15 | 16 | fn run() -> Result<()> { 17 | env_logger::init().unwrap(); 18 | 19 | let matches = App::new("geniza-sleep") 20 | .version(env!("CARGO_PKG_VERSION")) 21 | .subcommand( 22 | SubCommand::with_name("info") 23 | .about("Reads a SLEEP dir register and shows some basic metadata") 24 | .arg_from_usage(" 'directory containing files'") 25 | .arg_from_usage(" 'prefix for each data file'"), 26 | ) 27 | .subcommand( 28 | SubCommand::with_name("create") 29 | .about("Creates an SLEEP directory register (with header)") 30 | .arg_from_usage(" 'directory containing files'") 31 | .arg_from_usage(" 'prefix for each data file'"), 32 | ) 33 | .subcommand( 34 | SubCommand::with_name("chunk") 35 | .about("Dumps raw data for a single given chunk from a register (by index)") 36 | .arg_from_usage(" 'directory containing files'") 37 | .arg_from_usage(" 'prefix for each data file'") 38 | .arg_from_usage(" 'index of the data chunk to dump'"), 39 | ) 40 | .subcommand( 41 | SubCommand::with_name("verify") 42 | .about("Verifies the given register") 43 | .arg_from_usage(" 'directory containing files'") 44 | .arg_from_usage(" 'prefix for each data file'") 45 | ) 46 | .subcommand( 47 | SubCommand::with_name("file-info") 48 | .about("Reads a single SLEEP file and shows some basic metadata") 49 | .arg_from_usage(" 'SLEEP file to read'"), 50 | ) 51 | .subcommand( 52 | SubCommand::with_name("file-create") 53 | .about("Creates an empty single SLEEP file (with header)") 54 | .arg_from_usage(" 'SLEEP file to write (can't exist)'") 55 | .arg_from_usage(" 'Magic word to use (eg, 0x5025700)'") 56 | .arg_from_usage(" 'Size of each entry (bytes)'") 57 | .arg_from_usage(" 'Name of algorithm (empty string for none)'"), 58 | ) 59 | .subcommand( 60 | SubCommand::with_name("file-read-all") 61 | .about("Reads a single SLEEP file, iterates through all entries, prints raw bytes") 62 | .arg_from_usage(" 'SLEEP file to read'"), 63 | ) 64 | .subcommand( 65 | SubCommand::with_name("file-chunk") 66 | .about("Dumps raw data for a single given chunk from a SLEEP file (by index)") 67 | .arg_from_usage(" 'SLEEP file to read'") 68 | .arg_from_usage(" 'index of the data chunk to dump'"), 69 | ) 70 | .subcommand( 71 | SubCommand::with_name("write-example-alphabet") 72 | .about("Creates a content register in the given folder, with example data added") 73 | .arg_from_usage(" 'directory containing files'") 74 | .arg_from_usage(" 'prefix for each data file'") 75 | ) 76 | .get_matches(); 77 | 78 | 79 | match matches.subcommand() { 80 | ("info", Some(subm)) => { 81 | let dir = Path::new(subm.value_of("DIR").unwrap()); 82 | let prefix = subm.value_of("prefix").unwrap(); 83 | let mut sdr = SleepDirRegister::open(dir, prefix, false)?; 84 | println!("Entry count: {}", sdr.len()?); 85 | println!("Total size (bytes): {}", sdr.len_bytes()?); 86 | } 87 | ("create", Some(subm)) => { 88 | let dir = Path::new(subm.value_of("DIR").unwrap()); 89 | let prefix = subm.value_of("prefix").unwrap(); 90 | SleepDirRegister::create(dir, prefix)?; 91 | println!("Done!"); 92 | } 93 | ("chunk", Some(subm)) => { 94 | let dir = Path::new(subm.value_of("DIR").unwrap()); 95 | let prefix = subm.value_of("prefix").unwrap(); 96 | let index = value_t_or_exit!(subm, "index", u64); 97 | let mut sdr = SleepDirRegister::open(dir, prefix, false)?; 98 | println!("{:?}", sdr.get_data_entry(index)?); 99 | } 100 | ("verify", Some(subm)) => { 101 | let dir = Path::new(subm.value_of("DIR").unwrap()); 102 | let prefix = subm.value_of("prefix").unwrap(); 103 | let mut sdr = SleepDirRegister::open(dir, prefix, false)?; 104 | println!("{:?}", sdr.verify()); 105 | } 106 | ("file-info", Some(subm)) => { 107 | let path = Path::new(subm.value_of("FILE").unwrap()); 108 | let sf = SleepFile::open(path, false)?; 109 | println!("Magic: 0x{:X}", sf.get_magic()); 110 | println!( 111 | "Algorithm: '{}'", 112 | sf.get_algorithm().or(Some("".to_string())).unwrap() 113 | ); 114 | println!("Entry Size (bytes): {}", sf.get_entry_size()); 115 | println!("Entry count: {}", sf.len()?); 116 | } 117 | ("file-create", Some(subm)) => { 118 | let path = Path::new(subm.value_of("FILE").unwrap()); 119 | let algo_name = subm.value_of("algo_name").unwrap(); 120 | let algo_name = if algo_name.len() == 0 { 121 | None 122 | } else { 123 | Some(algo_name.to_string()) 124 | }; 125 | SleepFile::create( 126 | path, 127 | value_t_or_exit!(subm, "magic", u32), 128 | value_t_or_exit!(subm, "entry_size", u16), 129 | algo_name, 130 | )?; 131 | println!("Done!"); 132 | } 133 | ("file-read-all", Some(subm)) => { 134 | let path = Path::new(subm.value_of("FILE").unwrap()); 135 | let mut sf = SleepFile::open(path, false)?; 136 | for i in 0..sf.len()? { 137 | println!("{}: {:?}", i, sf.read(i)); 138 | } 139 | } 140 | ("file-chunk", Some(subm)) => { 141 | let path = Path::new(subm.value_of("FILE").unwrap()); 142 | let index = value_t_or_exit!(subm, "index", u64); 143 | let mut sf = SleepFile::open(path, false)?; 144 | //debug!(println!("{:?}", sdr)); 145 | println!("{:?}", sf.read(index)?); 146 | } 147 | ("write-example-alphabet", Some(subm)) => { 148 | let dir = Path::new(subm.value_of("DIR").unwrap()); 149 | let prefix = subm.value_of("prefix").unwrap(); 150 | let mut sdr = SleepDirRegister::create(dir, prefix)?; 151 | sdr.append(&[0x61; 1])?; // a 152 | sdr.append(&[0x62; 1])?; // b 153 | sdr.append(&[0x63; 1])?; // c 154 | sdr.append(&[0x64; 1])?; // d 155 | sdr.append(&[0x65; 1])?; // e 156 | sdr.append(&[0x66; 1])?; // f 157 | println!("Done!"); 158 | } 159 | _ => { 160 | println!("Missing or unimplemented command!"); 161 | println!("{}", matches.usage()); 162 | ::std::process::exit(-1); 163 | } 164 | } 165 | Ok(()) 166 | } 167 | 168 | quick_main!(run); 169 | -------------------------------------------------------------------------------- /src/bin/geniza-drive.rs: -------------------------------------------------------------------------------- 1 | // Free Software under GPL-3.0, see LICENSE 2 | // Copyright 2017 Bryan Newbold 3 | 4 | extern crate clap; 5 | extern crate env_logger; 6 | #[macro_use] 7 | extern crate error_chain; 8 | extern crate geniza; 9 | 10 | #[cfg(test)] 11 | extern crate assert_cli; 12 | 13 | use geniza::*; 14 | use std::path::Path; 15 | use clap::{App, Arg, SubCommand}; 16 | 17 | fn run() -> Result<()> { 18 | env_logger::init().unwrap(); 19 | 20 | let matches = App::new("geniza-drive") 21 | .version(env!("CARGO_PKG_VERSION")) 22 | .arg(Arg::with_name("dat-dir") 23 | .short("d") 24 | .long("dat-dir") 25 | .value_name("PATH") 26 | .help("dat drive directory") 27 | .default_value(".dat") 28 | .takes_value(true)) 29 | .subcommand( 30 | SubCommand::with_name("init") 31 | .about("Creates a blank drive") 32 | ) 33 | .subcommand( 34 | SubCommand::with_name("ls") 35 | .about("Lists current files in this dat") 36 | ) 37 | .subcommand( 38 | SubCommand::with_name("cat") 39 | .about("Prints a file (as a string) to stdout") 40 | .arg_from_usage(" 'file to add'") 41 | ) 42 | .subcommand( 43 | SubCommand::with_name("import-file") 44 | .about("Adds an indivudal file to the dat") 45 | .arg_from_usage(" 'file to add'") 46 | .arg_from_usage("--target 'path to import the file to (if not top level)'") 47 | ) 48 | .subcommand( 49 | SubCommand::with_name("export-file") 50 | .about("Copies a file from dat archive to local disk") 51 | .arg_from_usage(" 'file to export'") 52 | .arg_from_usage("--target 'path to save the file to (if not same name)'") 53 | ) 54 | .subcommand( 55 | SubCommand::with_name("import-dir") 56 | .about("Adds a directory (recursively) to the dat") 57 | .arg_from_usage(" 'directory to add'") 58 | .arg_from_usage("--target 'path to import the file to (if not top level)'") 59 | ) 60 | .subcommand( 61 | SubCommand::with_name("export-dir") 62 | .about("Copies a directory (recursively) from dat archive to local disk") 63 | .arg_from_usage(" 'directory to export'") 64 | .arg_from_usage("--target 'path to save the directory to (if not same name)'") 65 | ) 66 | .subcommand( 67 | SubCommand::with_name("log") 68 | .about("History of additions/deletions from this dat") 69 | ) 70 | .subcommand( 71 | SubCommand::with_name("verify") 72 | .about("Checks signatures et al") 73 | ) 74 | .subcommand( 75 | SubCommand::with_name("dump-entries") 76 | .about("Dump all entries in a debug-friendly format") 77 | ) 78 | .subcommand( 79 | SubCommand::with_name("copy") 80 | .about("Internally copies a file in a dat archive") 81 | .arg_from_usage(" 'path to copy from'") 82 | .arg_from_usage(" 'path to copy from'") 83 | ) 84 | .subcommand( 85 | SubCommand::with_name("remove") 86 | .about("Deletes a file path from dat archive") 87 | .arg_from_usage(" 'file to delete'") 88 | ) 89 | .subcommand( 90 | SubCommand::with_name("remove-dir-all") 91 | .about("Recursively deletes a directory from the dat archive") 92 | .arg_from_usage(" 'directory to delete'") 93 | ) 94 | .get_matches(); 95 | 96 | let dir = Path::new(matches.value_of("dat-dir").unwrap()); 97 | match matches.subcommand() { 98 | ("init", Some(_subm)) => { 99 | let _drive = DatDrive::create(dir)?; 100 | // TODO: print public key in hex 101 | println!("Done!"); 102 | } 103 | ("ls", Some(_subm)) => { 104 | let mut drive = DatDrive::open(dir, false)?; 105 | for entry in drive.read_dir_recursive("/") { 106 | let entry = entry?; 107 | println!("{}", entry.path.display()); 108 | } 109 | } 110 | ("cat", Some(subm)) => { 111 | let path = Path::new(subm.value_of("FILE").unwrap()); 112 | let mut drive = DatDrive::open(dir, true)?; 113 | let data = drive.read_file_bytes(&path)?; 114 | // TODO: just write to stdout 115 | let s = String::from_utf8(data).unwrap(); 116 | println!("{}", s); 117 | } 118 | ("import-file", Some(subm)) => { 119 | let path = Path::new(subm.value_of("FILE").unwrap()); 120 | let mut drive = DatDrive::open(dir, true)?; 121 | let fpath = match subm.value_of("target") { 122 | None => Path::new("/").join(path.file_name().unwrap()), 123 | Some(p) => Path::new("/").join(p) 124 | }; 125 | drive.import_file(&path, &fpath)?; 126 | 127 | } 128 | ("export-file", Some(subm)) => { 129 | let path = Path::new(subm.value_of("FILE").unwrap()); 130 | let mut drive = DatDrive::open(dir, true)?; 131 | let fpath = match subm.value_of("target") { 132 | None => Path::new("/").join(path.file_name().unwrap()), 133 | Some(p) => Path::new("/").join(p) 134 | }; 135 | drive.export_file(&path, &fpath)?; 136 | } 137 | ("import-dir", Some(subm)) => { 138 | let path = Path::new(subm.value_of("DIR").unwrap()); 139 | let mut drive = DatDrive::open(dir, true)?; 140 | let fpath = match subm.value_of("target") { 141 | None => Path::new("/").join(path.file_name().unwrap()), 142 | Some(p) => Path::new("/").join(p) 143 | }; 144 | drive.import_dir_all(&path, &fpath)?; 145 | 146 | } 147 | ("export-dir", Some(subm)) => { 148 | let path = Path::new(subm.value_of("DIR").unwrap()); 149 | let mut drive = DatDrive::open(dir, true)?; 150 | let fpath = match subm.value_of("target") { 151 | None => Path::new("/").join(path.file_name().unwrap()), 152 | Some(p) => Path::new("/").join(p) 153 | }; 154 | drive.export_dir(&path, &fpath)?; 155 | } 156 | ("log", Some(_subm)) => { 157 | let mut drive = DatDrive::open(dir, false)?; 158 | for entry in drive.history(0) { 159 | let entry = entry?; 160 | if let Some(stat) = entry.stat { 161 | if stat.get_blocks() == 0 { 162 | println!("{}\t[chg] {}", 163 | entry.index, entry.path.display()); 164 | } else { 165 | println!("{}\t[put] {}\t{} bytes ({} blocks)", 166 | entry.index, entry.path.display(), stat.get_size(), stat.get_blocks()); 167 | } 168 | } else { 169 | println!("{}\t[del] {}", 170 | entry.index, entry.path.display()); 171 | } 172 | } 173 | } 174 | ("verify", Some(_subm)) => { 175 | let mut drive = DatDrive::open(dir, false)?; 176 | println!("{:?}", drive.verify()); 177 | } 178 | ("dump-entries", Some(_subm)) => { 179 | let mut drive = DatDrive::open(dir, false)?; 180 | for entry in drive.history(0) { 181 | let entry = entry?; 182 | println!("{}\tpath: {}", 183 | entry.index, entry.path.display()); 184 | println!("\tchildren: {:?}", 185 | entry.children); 186 | if let Some(_) = entry.stat { 187 | println!("\tstat: Some (add/change)"); 188 | } else { 189 | println!("\tstat: None (delete)"); 190 | } 191 | } 192 | } 193 | ("copy", Some(subm)) => { 194 | let from_path= Path::new(subm.value_of("FROM").unwrap()); 195 | let to_path= Path::new(subm.value_of("FROM").unwrap()); 196 | let mut drive = DatDrive::open(dir, true)?; 197 | drive.copy_file(&from_path, &to_path)?; 198 | } 199 | ("remove", Some(subm)) => { 200 | let path = Path::new(subm.value_of("FILE").unwrap()); 201 | let mut drive = DatDrive::open(dir, true)?; 202 | drive.remove_file(&path)?; 203 | } 204 | ("remove-dir-all", Some(subm)) => { 205 | let path = Path::new(subm.value_of("FILE").unwrap()); 206 | let mut drive = DatDrive::open(dir, true)?; 207 | drive.remove_dir_all(&path)?; 208 | } 209 | _ => { 210 | println!("Missing or unimplemented command!"); 211 | println!("{}", matches.usage()); 212 | ::std::process::exit(-1); 213 | } 214 | } 215 | Ok(()) 216 | } 217 | 218 | quick_main!(run); 219 | 220 | #[test] 221 | fn test_drive_cmd() { 222 | 223 | assert_cli::Assert::cargo_binary("geniza-drive") 224 | .with_args(&["-d", "/non-existant-dir", "ls"]) 225 | .fails(); 226 | 227 | assert_cli::Assert::cargo_binary("geniza-drive") 228 | .with_args(&["-d", "test-data/dat/simple/.dat", "ls"]) 229 | .stdout().contains("README.md") 230 | .succeeds(); 231 | 232 | assert_cli::Assert::cargo_binary("geniza-drive") 233 | .with_args(&["-d", "test-data/dat/tree/.dat", "ls"]) 234 | .stdout().contains("Cantharellu") 235 | .succeeds(); 236 | 237 | assert_cli::Assert::cargo_binary("geniza-drive") 238 | .with_args(&["-d", "test-data/dat/alphabet/.dat", "cat", "/c"]) 239 | .stdout().is("c") 240 | .succeeds(); 241 | 242 | assert_cli::Assert::cargo_binary("geniza-drive") 243 | .with_args(&["-d", "test-data/dat/simple/.dat", "log"]) 244 | .stdout().contains("Felidae") 245 | .succeeds(); 246 | 247 | assert_cli::Assert::cargo_binary("geniza-drive") 248 | .with_args(&["-d", "test-data/dat/tree/.dat", "verify"]) 249 | .succeeds(); 250 | 251 | assert_cli::Assert::cargo_binary("geniza-drive") 252 | .with_args(&["-d", "test-data/dat/tree/.dat", "dump-entries"]) 253 | .succeeds(); 254 | 255 | } 256 | -------------------------------------------------------------------------------- /src/synchronizer.rs: -------------------------------------------------------------------------------- 1 | 2 | use errors::*; 3 | use network_msgs::*; 4 | use bitfield::*; 5 | use std::collections::HashMap; 6 | use std::path::{Path, PathBuf}; 7 | use protocol::{DatNetMessage, DatConnection}; 8 | use rand::{OsRng, Rng}; 9 | use sleep_register::HyperRegister; 10 | use peer::{DatPeerThread, PeerMsg}; 11 | use sleep_register::SleepDirRegister; 12 | use sodiumoxide::crypto::stream::Key; 13 | use bit_vec::BitVec; 14 | use discovery::discover_peers_dns; 15 | use protobuf::parse_from_bytes; 16 | use network_msgs::Data; 17 | use metadata_msgs::Index; 18 | use std::net::SocketAddr; 19 | use chan; 20 | 21 | pub enum SyncMode { 22 | RxMax, 23 | RxEndless, 24 | TxEndless, 25 | RxTxEndless, 26 | } 27 | 28 | pub struct RegisterStatus { 29 | id: u8, 30 | register: SleepDirRegister, 31 | inflight: Vec, 32 | wanted: BitVec, 33 | key: Key, 34 | } 35 | 36 | pub struct Synchronizer { 37 | peers: HashMap, 38 | registers: Vec, 39 | mode: SyncMode, 40 | is_drive: bool, 41 | local_id: [u8; 32], 42 | dir: Option, 43 | unified_peers_tx: chan::Sender>, 44 | unified_peers_rx: chan::Receiver>, 45 | potential_peers: Vec, 46 | } 47 | 48 | impl Synchronizer { 49 | 50 | pub fn new_downloader(key: Key, mode: SyncMode, dir: &Path) -> Result { 51 | 52 | let metadata_reg = SleepDirRegister::create(dir.as_ref(), "metadata")?; 53 | 54 | let (unified_peers_tx, unified_peers_rx) = chan::async(); 55 | 56 | let metadata_status = RegisterStatus { 57 | id: 0, 58 | register: metadata_reg, 59 | inflight: vec![], 60 | wanted: BitVec::new(), 61 | key, 62 | }; 63 | 64 | let mut rng = OsRng::new()?; 65 | let mut local_id = [0; 32]; 66 | rng.fill_bytes(&mut local_id); 67 | 68 | let s = Synchronizer { 69 | peers: HashMap::new(), 70 | mode, 71 | local_id, 72 | is_drive: true, 73 | dir: Some(dir.to_path_buf()), 74 | registers: vec![metadata_status], 75 | unified_peers_tx, 76 | unified_peers_rx, 77 | potential_peers: vec![], 78 | }; 79 | Ok(s) 80 | } 81 | 82 | pub fn discover(&mut self) -> Result { 83 | 84 | let meta_key = &self.registers.get(0).unwrap().key.clone(); 85 | let new_peers = discover_peers_dns(&meta_key[0..32])?; 86 | let new_count = new_peers.len() as u64; 87 | 88 | for p in new_peers { 89 | self.add_peer(p); 90 | } 91 | Ok(new_count) 92 | } 93 | 94 | pub fn add_peer(&mut self, sa: SocketAddr) { 95 | 96 | if !self.potential_peers.contains(&sa) { 97 | self.potential_peers.push(sa); 98 | } 99 | } 100 | 101 | pub fn run(&mut self) -> Result<()> { 102 | 103 | let meta_key = &self.registers.get(0).unwrap().key.clone(); 104 | let mut rng = OsRng::new()?; 105 | for p in &self.potential_peers { 106 | // TODO: somewhere in here validate that we haven't already connected to this peer id 107 | // by a different name 108 | let handle = rng.gen::(); 109 | let pt = DatPeerThread::connect(p, meta_key.clone(), handle, false, Some(&self.local_id), self.unified_peers_tx.clone())?; 110 | self.peers.insert(handle, pt); 111 | let pt = self.peers.get_mut(&handle).unwrap(); 112 | 113 | match self.mode { 114 | SyncMode::RxMax => { 115 | init_want_everything(pt, 0)?; 116 | }, 117 | SyncMode::RxEndless => unimplemented!(), 118 | SyncMode::TxEndless => unimplemented!(), 119 | SyncMode::RxTxEndless => unimplemented!(), 120 | }; 121 | }; 122 | 123 | // bug in chan_select!() breaking `self` reference? 124 | // "recursion limit reached while expanding the macro `chan_select`" 125 | let unified_peers_rx = self.unified_peers_rx.clone(); 126 | 127 | loop { 128 | chan_select! { 129 | unified_peers_rx.recv() -> val => { 130 | if let Some(Ok(pm)) = val { 131 | self.handle_msg(&pm)?; 132 | } 133 | }, 134 | }; 135 | } 136 | } 137 | 138 | fn handle_msg(&mut self, pm: &PeerMsg) -> Result<()> { 139 | // NB: this is the simplistic model of registers (only works up to 2x per peer) 140 | 141 | // mutable ref to PeerThread for this message 142 | let pt = self.peers.get_mut(&pm.peer_handle).unwrap(); 143 | 144 | // NB: this is the simplistic model of registers (only works up to 2x per peer?) 145 | if pm.feed_index as usize >= self.registers.len() { 146 | // Ignore feed channels we haven't registered yet 147 | return Ok(()); 148 | } 149 | 150 | match &pm.msg { 151 | &DatNetMessage::Feed(_) => { unimplemented!() }, 152 | &DatNetMessage::Handshake(_) => { unimplemented!() }, 153 | &DatNetMessage::Info(_) => { unimplemented!() }, 154 | &DatNetMessage::Have(ref msg) => { 155 | // TODO: depending on mode... 156 | 157 | //let peer_has = extract_bitfield(msg)?; 158 | // TODO: remove bits we already have 159 | // TODO: depending on mode, extend 'wanted' bits 160 | // TODO: send a Request on this channel 161 | // XXX: dummy for testing 162 | let mut request = Request::new(); 163 | request.set_index(msg.get_start()); 164 | pt.send(DatNetMessage::Request(request), pm.feed_index)?; 165 | }, 166 | &DatNetMessage::Unhave(_) => {}, // PASS 167 | &DatNetMessage::Want(_) => {}, // PASS 168 | &DatNetMessage::Unwant(_) => {}, // PASS 169 | &DatNetMessage::Request(_) => {}, // PASS 170 | &DatNetMessage::Cancel(_) => {}, // PASS 171 | &DatNetMessage::Data(ref msg) => { 172 | 173 | // TODO: feed indexing? 174 | // Insert into local feed 175 | // XXX self.registers[pm.feed_index].insert(msg); 176 | 177 | // If a drive, and this is the first entry of metadata feed, it has the config for 178 | // the content feed 179 | if self.is_drive && pm.feed_index == 0 && msg.get_index() == 0 { 180 | let data_key = parse_drive_data_key(msg)?; 181 | pt.add_feed(&data_key)?; 182 | init_want_everything(pt, 1)?; 183 | 184 | // If we haven't already, create and save a local register 185 | if self.registers.len() < 2 { 186 | 187 | let dir = self.dir.clone().unwrap(); 188 | let content_reg = SleepDirRegister::create(&dir, "content")?; 189 | 190 | let content_status = RegisterStatus { 191 | id: 1, 192 | register: content_reg, 193 | inflight: vec![], 194 | wanted: BitVec::new(), 195 | key: data_key, 196 | }; 197 | 198 | self.registers.push(content_status); 199 | } 200 | } 201 | 202 | // TODO: send next wanted, or otherwise update state 203 | }, 204 | } 205 | Ok(()) 206 | } 207 | } 208 | 209 | fn parse_drive_data_key(data_msg: &Data) -> Result { 210 | let index_msg = parse_from_bytes::(&mut data_msg.get_value())?; 211 | if index_msg.get_field_type() == "hyperdrive" { 212 | let data_key = index_msg.get_content(); 213 | if data_key.len() != 32 { 214 | bail!("Received data key had wrong length: {}", data_key.len()); 215 | } 216 | return Ok(Key::from_slice(&data_key[0..32]).unwrap()); 217 | } else { 218 | bail!("non-hyperdrive Index type: {}", index_msg.get_field_type()); 219 | } 220 | } 221 | 222 | 223 | fn max_index(have_msg: &Have) -> Result { 224 | if have_msg.has_length() { 225 | return Ok(have_msg.get_start() + have_msg.get_length()); 226 | } else if have_msg.has_bitfield() { 227 | let raw_bf = have_msg.get_bitfield(); 228 | let bf = decode_bitfield(raw_bf)?; 229 | trace!("decoded bitfield: {:?}", bf); 230 | return Ok(max_high_bit(&bf)); 231 | } else { 232 | return Ok(have_msg.get_start() + 1); 233 | } 234 | } 235 | 236 | #[test] 237 | fn test_max_index() { 238 | let mut hm = Have::new(); 239 | hm.set_start(0); 240 | hm.set_bitfield(vec![7,2,128]); 241 | assert_eq!(max_index(&hm).unwrap(), 8); 242 | 243 | hm.set_bitfield(vec![2, 207]); 244 | assert_eq!(max_index(&hm).unwrap(), 7); 245 | 246 | // Alphabet test dat 247 | hm.set_bitfield(vec![2, 254]); 248 | assert_eq!(max_index(&hm).unwrap(), 6); 249 | hm.set_bitfield(vec![2, 252]); 250 | assert_eq!(max_index(&hm).unwrap(), 5); 251 | } 252 | 253 | fn init_want_everything(dpt: &mut DatPeerThread, reg_index: u8) -> Result<()> { 254 | 255 | // Info: downloading, not uploading 256 | let mut im = Info::new(); 257 | im.set_uploading(false); 258 | im.set_downloading(true); 259 | let im = DatNetMessage::Info(im); 260 | dpt.send(im, reg_index)?; 261 | 262 | // Have: nothing (so far) 263 | let mut hm = Have::new(); 264 | hm.set_start(0); 265 | hm.set_length(0); 266 | let hm = DatNetMessage::Have(hm); 267 | dpt.send(hm, reg_index)?; 268 | 269 | // UnHave: still nothing 270 | let mut uhm = Unhave::new(); 271 | uhm.set_start(0); 272 | let uhm = DatNetMessage::Unhave(uhm); 273 | dpt.send(uhm, reg_index)?; 274 | 275 | // Want: everything 276 | let mut wm = Want::new(); 277 | wm.set_start(0); 278 | let wm = DatNetMessage::Want(wm); 279 | dpt.send(wm, reg_index)?; 280 | 281 | Ok(()) 282 | } 283 | 284 | /// Tries to connect to a single peer, pull register, and close. 285 | pub fn node_simple_clone(host_port: &str, key: &[u8], register: &mut dyn HyperRegister, reg_index: u8) -> Result<()> { 286 | 287 | if register.len()? > 0 { 288 | bail!("Register already had data in it (expected empty for naive clone)"); 289 | } 290 | 291 | let key = Key::from_slice(key).unwrap(); 292 | let mut dc = DatConnection::connect(host_port, &key, false, None)?; 293 | 294 | // Info: downloading, not uploading 295 | let mut im = Info::new(); 296 | im.set_uploading(false); 297 | im.set_downloading(true); 298 | let im = DatNetMessage::Info(im); 299 | dc.send_msg(&im, reg_index)?; 300 | 301 | // Have: nothing (so far) 302 | let mut hm = Have::new(); 303 | hm.set_start(0); 304 | hm.set_length(0); 305 | let hm = DatNetMessage::Have(hm); 306 | dc.send_msg(&hm, reg_index)?; 307 | 308 | // UnHave: still nothing 309 | let mut uhm = Unhave::new(); 310 | uhm.set_start(0); 311 | let uhm = DatNetMessage::Unhave(uhm); 312 | dc.send_msg(&uhm, reg_index)?; 313 | 314 | // Want: everything 315 | let mut wm = Want::new(); 316 | wm.set_start(0); 317 | let wm = DatNetMessage::Want(wm); 318 | dc.send_msg(&wm, reg_index)?; 319 | 320 | let last_entry: u64; 321 | 322 | // Receive Have messages to determine lengths 323 | loop { 324 | let (msg, got_reg_index) = dc.recv_msg()?; 325 | match msg { 326 | DatNetMessage::Have(dh) => { 327 | info!("reg_index={}; {:?}; bitfield={:?}", got_reg_index, dh, dh.get_bitfield()); 328 | last_entry = max_index(&dh)?; 329 | break; 330 | }, 331 | _ => { 332 | info!("Other message: {:?}", &msg); 333 | } 334 | } 335 | } 336 | 337 | info!("last_entry={}", last_entry); 338 | 339 | // Request / Data loops 340 | for i in 0..(last_entry+1) { 341 | let mut rm = Request::new(); 342 | rm.set_index(i); 343 | info!("Sending request: {:?}", rm); 344 | dc.send_msg(&DatNetMessage::Request(rm), 0)?; 345 | let (msg, got_reg_index) = dc.recv_msg()?; 346 | assert!(got_reg_index == 0); 347 | match msg { 348 | DatNetMessage::Data(dm) => { 349 | info!("Got data: index={}", dm.get_index()); 350 | assert!(dm.has_value()); 351 | assert!(dm.get_index() == i); 352 | register.append(dm.get_value())?; 353 | }, 354 | _ => { 355 | info!("Other message: {:?}", &msg); 356 | } 357 | } 358 | } 359 | Ok(()) 360 | } 361 | -------------------------------------------------------------------------------- /src/protocol.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::net::{TcpStream, ToSocketAddrs, Shutdown}; 3 | use std::time::Duration; 4 | use std::io::{Read, Write}; 5 | use std::cmp; 6 | use std::fmt::Display; 7 | use sodiumoxide::crypto::stream::*; 8 | use rand::{OsRng, Rng}; 9 | use protobuf::Message; 10 | use protobuf::parse_from_bytes; 11 | use integer_encoding::{VarIntReader, VarIntWriter}; 12 | 13 | use errors::*; 14 | use network_msgs::*; 15 | use make_discovery_key; 16 | 17 | #[derive(Debug)] 18 | pub enum DatNetMessage { 19 | Feed(Feed), 20 | Handshake(Handshake), 21 | Info(Info), 22 | Have(Have), 23 | Unhave(Unhave), 24 | Want(Want), 25 | Unwant(Unwant), 26 | Request(Request), 27 | Cancel(Cancel), 28 | Data(Data), 29 | } 30 | 31 | fn msg_code(msg: &DatNetMessage) -> u8 { 32 | match msg { 33 | &DatNetMessage::Feed(_) => 0, 34 | &DatNetMessage::Handshake(_) => 1, 35 | &DatNetMessage::Info(_) => 2, 36 | &DatNetMessage::Have(_) => 3, 37 | &DatNetMessage::Unhave(_) => 4, 38 | &DatNetMessage::Want(_) => 5, 39 | &DatNetMessage::Unwant(_) => 6, 40 | &DatNetMessage::Request(_) => 7, 41 | &DatNetMessage::Cancel(_) => 8, 42 | &DatNetMessage::Data(_) => 9, 43 | } 44 | } 45 | 46 | fn msg_sugar(msg: &DatNetMessage) -> &dyn Message { 47 | match msg { 48 | &DatNetMessage::Feed(ref m) => m, 49 | &DatNetMessage::Handshake(ref m) => m, 50 | &DatNetMessage::Info(ref m) => m, 51 | &DatNetMessage::Have(ref m) => m, 52 | &DatNetMessage::Unhave(ref m) => m, 53 | &DatNetMessage::Want(ref m) => m, 54 | &DatNetMessage::Unwant(ref m) => m, 55 | &DatNetMessage::Request(ref m) => m, 56 | &DatNetMessage::Cancel(ref m) => m, 57 | &DatNetMessage::Data(ref m) => m, 58 | } 59 | } 60 | 61 | /// This helper is pretty slow/inefficient; lots of copying memory 62 | fn bytewise_stream_xor_ic_inplace(buf: &mut [u8], byte_offset: u64, nonce: &Nonce, key: &Key) { 63 | // TODO: switch to new stream_xor_ic_inplace() variant? 64 | let mut offset = byte_offset; 65 | 66 | // We may have a partial-64-byte-block to finish encrypting first 67 | let partial_offset: usize = (offset % 64) as usize; 68 | let partial_len: usize = cmp::min(64 - partial_offset, buf.len()); 69 | if partial_len != 0 { 70 | let mut partial = vec![0; 64]; 71 | for i in 0..partial_len { 72 | partial[partial_offset + i] = buf[i]; 73 | } 74 | let partial_enc = stream_xor_ic(&partial, &nonce, offset / 64, &key); 75 | offset += partial_len as u64; 76 | for i in 0..partial_len { 77 | buf[i] = partial_enc[partial_offset + i]; 78 | } 79 | } 80 | if buf.len() > partial_len { 81 | let main_enc = stream_xor_ic(&buf[partial_len..], &nonce, offset / 64, &key); 82 | //offset += main_enc.len() as u64; 83 | for i in 0..main_enc.len() { 84 | buf[partial_len + i] = main_enc[i]; 85 | } 86 | } 87 | } 88 | 89 | #[test] 90 | fn test_bsxii_short() { 91 | let nonce = gen_nonce(); 92 | let key = gen_key(); 93 | 94 | for size in [10, 100, 1234].iter() { 95 | let mut a = vec![7; *size]; 96 | let mut b = vec![7; *size]; 97 | let c = vec![7; *size]; 98 | 99 | assert_eq!(a, b); 100 | bytewise_stream_xor_ic_inplace(&mut a, 0, &nonce, &key); 101 | bytewise_stream_xor_ic_inplace(&mut b, 0, &nonce, &key); 102 | assert_eq!(a, b); 103 | assert_ne!(a, c); 104 | bytewise_stream_xor_ic_inplace(&mut a, 0, &nonce, &key); 105 | assert_eq!(a, c); 106 | } 107 | } 108 | 109 | #[test] 110 | fn test_bsxii_continued() { 111 | let nonce = gen_nonce(); 112 | let key = gen_key(); 113 | 114 | let mut a = vec![7; 1234]; 115 | let mut b = vec![7; 1234]; 116 | let c = vec![7; 1234]; 117 | 118 | assert_eq!(a, b); 119 | bytewise_stream_xor_ic_inplace(&mut a[0..10], 0, &nonce, &key); 120 | bytewise_stream_xor_ic_inplace(&mut a[10..20], 10, &nonce, &key); 121 | bytewise_stream_xor_ic_inplace(&mut b[0..20], 0, &nonce, &key); 122 | assert_eq!(a, b); 123 | bytewise_stream_xor_ic_inplace(&mut a[20..50], 20, &nonce, &key); 124 | bytewise_stream_xor_ic_inplace(&mut a[50..500], 50, &nonce, &key); 125 | bytewise_stream_xor_ic_inplace(&mut b[20..500], 20, &nonce, &key); 126 | assert_ne!(a, c); 127 | assert_eq!(a, b); 128 | bytewise_stream_xor_ic_inplace(&mut a[500..1234], 500, &nonce, &key); 129 | bytewise_stream_xor_ic_inplace(&mut a, 0, &nonce, &key); 130 | assert_eq!(a, c); 131 | } 132 | 133 | /// Represents a bi-directional connection to a network peer 134 | /// 135 | /// Spec says nonce is 32 bytes, by dat implementation (hypercore-protocol) is 24 bytes. 136 | pub struct DatConnection { 137 | pub id: [u8; 32], 138 | remote_id: [u8; 32], 139 | pub tcp: TcpStream, 140 | pub live: bool, 141 | pub key: Key, 142 | pub discovery_key: [u8; 32], 143 | tx_nonce: Nonce, 144 | tx_offset: u64, 145 | rx_nonce: Nonce, 146 | rx_offset: u64, 147 | } 148 | 149 | impl Read for DatConnection { 150 | /// Encrypted TCP read (after connection initialized). Uses XOR of an XSalsa20 stream, using 151 | /// block offsets. 152 | fn read(&mut self, buf: &mut [u8]) -> ::std::io::Result { 153 | let len = self.tcp.read(buf)?; 154 | bytewise_stream_xor_ic_inplace(&mut buf[0..len], self.rx_offset, &self.rx_nonce, &self.key); 155 | self.rx_offset += len as u64; 156 | 157 | Ok(len) 158 | } 159 | } 160 | 161 | impl Write for DatConnection { 162 | /// Encrypted write to complement `read()`. 163 | fn write(&mut self, buf: &[u8]) -> ::std::io::Result { 164 | // Don't mutate what we've been passed 165 | let mut enc = vec![0; buf.len()]; 166 | enc.copy_from_slice(buf); 167 | 168 | bytewise_stream_xor_ic_inplace(&mut enc, self.tx_offset, &self.tx_nonce, &self.key); 169 | self.tx_offset += enc.len() as u64; 170 | 171 | self.tcp.write(&enc) 172 | } 173 | 174 | fn flush(&mut self) -> ::std::io::Result<()> { 175 | self.tcp.flush() 176 | } 177 | } 178 | 179 | impl Clone for DatConnection { 180 | fn clone(&self) -> DatConnection { 181 | DatConnection { 182 | id: self.id.clone(), 183 | remote_id: self.remote_id.clone(), 184 | tcp: self.tcp.try_clone().unwrap(), 185 | live: self.live, 186 | key: self.key.clone(), 187 | discovery_key: self.discovery_key.clone(), 188 | tx_nonce: self.tx_nonce.clone(), 189 | tx_offset: self.tx_offset, 190 | rx_nonce: self.rx_nonce.clone(), 191 | rx_offset: self.rx_offset, 192 | 193 | } 194 | } 195 | } 196 | 197 | impl DatConnection { 198 | pub fn connect(addr: A, key: &Key, live: bool, local_id: Option<&[u8]>) -> Result { 199 | 200 | // Connect to server 201 | info!("Connecting to {}", addr); 202 | // TODO: timeout on connect (socketaddr iterator dance) 203 | let tcp = TcpStream::connect(addr)?; 204 | 205 | DatConnection::from_tcp(tcp, key, live, local_id) 206 | } 207 | 208 | // It's sort of a hack, but this should be usable from an accept() as well as a connect() 209 | pub fn from_tcp(tcp: TcpStream, key: &Key, live: bool, local_id: Option<&[u8]>) -> Result { 210 | 211 | let tx_nonce = gen_nonce(); 212 | let mut rng = OsRng::new()?; 213 | let local_id = match local_id { 214 | Some(val) => { 215 | let mut buf = [0; 32]; 216 | buf.copy_from_slice(val); 217 | buf 218 | }, 219 | None => { 220 | let mut buf = [0; 32]; 221 | rng.fill_bytes(&mut buf); 222 | buf 223 | }, 224 | }; 225 | 226 | let mut dk = [0; 32]; 227 | dk.copy_from_slice(&make_discovery_key(&key[0..32])[0..32]); 228 | 229 | let timeout = Duration::new(7, 0); 230 | tcp.set_write_timeout(Some(timeout))?; 231 | 232 | let mut dc = DatConnection { 233 | id: local_id, 234 | tcp, 235 | live, 236 | remote_id: [0; 32], 237 | key: key.clone(), 238 | discovery_key: dk, 239 | tx_nonce: tx_nonce, 240 | tx_offset: 0, 241 | rx_nonce: gen_nonce(), // dummy 242 | rx_offset: 0, 243 | }; 244 | 245 | // Exchange feed 246 | let mut feed_msg = Feed::new(); 247 | feed_msg.set_discoveryKey(dc.discovery_key.to_vec()); 248 | feed_msg.set_nonce((tx_nonce[0..24]).to_vec()); 249 | dc.send_feed(&feed_msg)?; 250 | 251 | // read feed 252 | let registration = dc.recv_feed()?; 253 | if registration.get_discoveryKey()[0..32] != dk[..] { 254 | bail!("Remote peer not sharing same discovery key"); 255 | } 256 | let rn = registration.get_nonce(); 257 | dc.rx_nonce = Nonce::from_slice(&rn).unwrap(); 258 | 259 | // send handshake 260 | let mut handshake_msg = Handshake::new(); 261 | handshake_msg.set_live(dc.live); 262 | handshake_msg.set_id(dc.id.to_vec()); 263 | dc.send_msg(&DatNetMessage::Handshake(handshake_msg), 0)?; 264 | 265 | // read handshake 266 | let (msg, feed_index) = dc.recv_msg()?; 267 | if feed_index == 1 { 268 | bail!("Expected metadata msg, not content"); 269 | } 270 | if let DatNetMessage::Handshake(handshake) = msg { 271 | // TODO: more satisfying way to do this copy 272 | let hid = handshake.get_id(); 273 | for i in 0..32 { 274 | dc.remote_id[i] = hid[i]; 275 | } 276 | } else { 277 | bail!("Expected Handshake message, got something else"); 278 | } 279 | 280 | Ok(dc) 281 | } 282 | 283 | /// For hyperdrive connections, `feed_index` is equivalent to a `is_content` boolean flag. 284 | pub fn send_msg(&mut self, dnm: &DatNetMessage, feed_index: u8) -> Result<()> { 285 | let header_int: u8 = (feed_index as u8) << 4 | (msg_code(dnm) & 0x0F); 286 | let msg: &dyn Message = msg_sugar(dnm); 287 | let total_message_size = (msg.compute_size() as usize) + 1; 288 | 289 | trace!( 290 | "SEND total_len={} header={} feed_index={} type={:?}", 291 | total_message_size, 292 | header_int, 293 | feed_index, 294 | &dnm 295 | ); 296 | 297 | // send both header varints, and data 298 | self.write_varint(total_message_size as u64)?; 299 | self.write_varint(header_int as u32)?; 300 | 301 | match dnm { 302 | &DatNetMessage::Feed(ref m) => m.write_to_writer(self)?, 303 | &DatNetMessage::Handshake(ref m) => m.write_to_writer(self)?, 304 | &DatNetMessage::Info(ref m) => m.write_to_writer(self)?, 305 | &DatNetMessage::Have(ref m) => m.write_to_writer(self)?, 306 | &DatNetMessage::Unhave(ref m) => m.write_to_writer(self)?, 307 | &DatNetMessage::Want(ref m) => m.write_to_writer(self)?, 308 | &DatNetMessage::Unwant(ref m) => m.write_to_writer(self)?, 309 | &DatNetMessage::Request(ref m) => m.write_to_writer(self)?, 310 | &DatNetMessage::Cancel(ref m) => m.write_to_writer(self)?, 311 | &DatNetMessage::Data(ref m) => m.write_to_writer(self)?, 312 | } 313 | Ok(()) 314 | } 315 | 316 | /// Returns a tuple of the received message and the register index it corresponds to. 317 | pub fn recv_msg(&mut self) -> Result<(DatNetMessage, u8)> { 318 | let total_len: u64 = self.read_varint()?; 319 | let header: u8 = self.read_varint()?; 320 | 321 | let feed_index = (header >> 4) & 0xFF; 322 | 323 | trace!( 324 | "RECV total_len={} header={} feed_index={}", 325 | total_len, 326 | header, 327 | feed_index, 328 | ); 329 | 330 | if header > 0x1F { 331 | bail!("Invalid header received: {}", header); 332 | } 333 | 334 | let msg_len = (total_len - 1) as usize; 335 | let mut buf = vec![0; msg_len]; 336 | self.read_exact(&mut buf[0..msg_len])?; 337 | 338 | let dnm = match header & 0x0F { 339 | 0 => DatNetMessage::Feed(parse_from_bytes::(&mut buf)?), 340 | 1 => DatNetMessage::Handshake(parse_from_bytes::(&mut buf)?), 341 | 2 => DatNetMessage::Info(parse_from_bytes::(&mut buf)?), 342 | 3 => DatNetMessage::Have(parse_from_bytes::(&mut buf)?), 343 | 4 => DatNetMessage::Unhave(parse_from_bytes::(&mut buf)?), 344 | 5 => DatNetMessage::Want(parse_from_bytes::(&mut buf)?), 345 | 6 => DatNetMessage::Unwant(parse_from_bytes::(&mut buf)?), 346 | 7 => DatNetMessage::Request(parse_from_bytes::(&mut buf)?), 347 | 8 => DatNetMessage::Cancel(parse_from_bytes::(&mut buf)?), 348 | 9 => DatNetMessage::Data(parse_from_bytes::(&mut buf)?), 349 | other => bail!("Unimplemented message type received: {}", other), 350 | }; 351 | trace!("\twas: {:?}", &dnm); 352 | Ok((dnm, feed_index)) 353 | } 354 | 355 | /// Special unencrypted variant of `send_msg()`, used only during initial connection 356 | /// establishment (eg, to check metadata discovery key and exchange nonces). After the 357 | /// connection is initialized, send Feed messages as normal to add extra feeds. 358 | fn send_feed(&mut self, reg: &Feed) -> Result<()> { 359 | // TODO: refactor this to take discovery key and nonce directly 360 | 361 | let header_int: u8 = 0; 362 | let total_message_size = (reg.compute_size() as usize) + 1; 363 | 364 | trace!( 365 | "SEND total_len={} header={} msg={:?}", 366 | total_message_size, 367 | header_int, 368 | reg 369 | ); 370 | 371 | self.tcp.write_varint(total_message_size as u64)?; 372 | self.tcp.write_varint(header_int as u32)?; 373 | reg.write_to_writer(&mut self.tcp)?; 374 | Ok(()) 375 | } 376 | 377 | /// Receive complement to `send_feed()` (un-encrypted, used only during initial connection 378 | /// establishment). 379 | fn recv_feed(&mut self) -> Result { 380 | 381 | let total_len: u64 = self.tcp.read_varint()?; 382 | let header: u8 = self.tcp.read_varint()?; 383 | 384 | if header != 0 { 385 | bail!("Invalid Feed header received"); 386 | } 387 | 388 | trace!("RECV total_len={} header={}", total_len, header); 389 | 390 | let msg_len = (total_len - 1) as usize; 391 | let mut buf = vec![0; msg_len]; 392 | self.tcp.read_exact(&mut buf[0..msg_len])?; 393 | 394 | let reg = parse_from_bytes::(&mut buf)?; 395 | trace!("\twas: {:?}", reg); 396 | Ok(reg) 397 | } 398 | 399 | pub fn close(&mut self) { 400 | self.tcp.shutdown(Shutdown::Both); 401 | } 402 | } 403 | -------------------------------------------------------------------------------- /src/sleep_register.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::io::prelude::*; 3 | use std::fs::File; 4 | use std::path::{Path, PathBuf}; 5 | use std::io::SeekFrom; 6 | use std::os::unix::fs::FileExt; 7 | use integer_encoding::FixedInt; 8 | use std::fs::OpenOptions; 9 | use crypto::blake2b::Blake2b; 10 | use crypto::digest::Digest; 11 | use crypto::ed25519; 12 | use rand::{OsRng, Rng}; 13 | 14 | use errors::*; 15 | use sleep_file::*; 16 | use make_discovery_key; 17 | 18 | /// Abstract access to Hypercore register 19 | pub trait HyperRegister { 20 | /// Whether the register store contains the given (data) entry 21 | fn has(&self, entry_index: u64) -> Result; 22 | 23 | /// Whether the register store contains *all* known (data) entries 24 | fn has_all(&self) -> Result; 25 | 26 | /// If the contiguous range of entries is in the store 27 | fn has_range(&self, start: u64, end: u64) -> Result; 28 | 29 | /// Reads a single data entry from the store. 30 | fn get_data_entry(&mut self, entry_index: u64) -> Result>; 31 | 32 | /// Writes an entry to the store. Requires the private key to be present. Returns the entry 33 | /// index written to. 34 | fn append(&mut self, data: &[u8]) -> Result; 35 | 36 | /// Count of data entries for this register. This is the total count (highest entry index plus 37 | /// one); this particular store might be sparse. 38 | fn len(&self) -> Result; 39 | 40 | /// Total size of this register in bytes. 41 | fn len_bytes(&mut self) -> Result; 42 | 43 | /// Intended to do a deeper merkel-tree verification of all stored data 44 | fn verify(&mut self) -> Result<()>; 45 | 46 | /// Quick sanity checks on register store robust-ness 47 | fn check(&mut self) -> Result<()>; 48 | 49 | /// Can this register be appended to? 50 | fn writable(&self) -> bool; 51 | 52 | /// Returns a single tree entry (using tree indexing, not data indexing). 53 | fn get_tree_entry(&mut self, tree_index: u64) -> Result>; 54 | } 55 | 56 | impl dyn HyperRegister { 57 | fn hash_leaf(data: &[u8]) -> [u8; 40] { 58 | let mut buf = [0; 40]; 59 | u64::to_be(data.len() as u64).encode_fixed(&mut buf[32..40]); 60 | let mut hash = Blake2b::new(32); 61 | hash.input(&[0; 1]); 62 | hash.input(&buf[32..40]); 63 | hash.input(&data); 64 | hash.result(&mut buf[0..32]); 65 | buf 66 | } 67 | 68 | fn hash_parent(lhash: &[u8], rhash: &[u8]) -> [u8; 40] { 69 | let mut buf = [0; 40]; 70 | // TODO: check overflow 71 | let sum_size = u64::from_be(FixedInt::decode_fixed(&lhash[32..40])) 72 | + u64::from_be(FixedInt::decode_fixed(&rhash[32..40])); 73 | u64::to_be(sum_size as u64).encode_fixed(&mut buf[32..40]); 74 | 75 | let mut hash = Blake2b::new(32); 76 | hash.input(&[1; 1]); 77 | hash.input(&buf[32..40]); 78 | hash.input(&lhash[0..32]); 79 | hash.input(&rhash[0..32]); 80 | hash.result(&mut buf[0..32]); 81 | buf 82 | } 83 | 84 | /// Hashes all the tree root parents for the given entry index (data index, not tree index). 85 | pub fn hash_roots(reg: &mut dyn HyperRegister, entry_index: u64) -> Result> { 86 | let mut buf = [0; 32]; 87 | let mut hash = Blake2b::new(32); 88 | let mut index_buf = [0; 8]; 89 | hash.input(&[2; 1]); 90 | for ri in HyperRegister::tree_root_nodes(entry_index + 1) { 91 | u64::to_be(ri).encode_fixed(&mut index_buf); 92 | let node = reg.get_tree_entry(ri)?; 93 | hash.input(&node[0..32]); 94 | hash.input(&index_buf); 95 | hash.input(&node[32..40]); 96 | } 97 | hash.result(&mut buf); 98 | Ok(buf.to_vec()) 99 | } 100 | 101 | /// Calculates the root notes for a given length (of data entries, not tree entries) 102 | fn tree_root_nodes(data_count: u64) -> Vec { 103 | // TODO: this should be an iterator 104 | // NB: this is a relatively "hot" function, gets called (repeatedly?) on every mutation, 105 | // and potentially in inner loops of lookups. 106 | if data_count == 0 { 107 | return vec![]; 108 | } 109 | 110 | // Convert the count to a (descending) list of power-of-2 components 111 | let mut x = 0; 112 | let mut components = vec![]; 113 | while 2u64.pow(x) <= data_count { 114 | if (data_count & 2u64.pow(x)) != 0 { 115 | components.push(2u64.pow(x)); 116 | } 117 | x += 1; 118 | } 119 | components.reverse(); 120 | 121 | // Add and accumulate 122 | let mut accum = 0; 123 | let mut roots = vec![]; 124 | for x in components { 125 | roots.push(accum + (x - 1)); 126 | accum += 2 * x; 127 | } 128 | roots 129 | } 130 | 131 | /// Finds the offset of the given data chunk in the linear appended data file (not a "checked 132 | /// out" individual file) 133 | pub fn get_data_offset(reg: &mut dyn HyperRegister, entry_index: u64) -> Result { 134 | // TODO: this is a naive (linear) implementation 135 | // log(N) would go up previous parent nodes (eg, use root_nodes()) 136 | let mut sum: u64 = 0; 137 | for i in 0..entry_index { 138 | let leaf = reg.get_tree_entry(i * 2)?; 139 | sum += u64::from_be(FixedInt::decode_fixed(&leaf[32..40])); 140 | } 141 | Ok(sum) 142 | } 143 | 144 | /// Every node has a parent, so this function won't fail unless index is over 2^62, in which 145 | /// case it would overflow and panics instead. 146 | fn tree_parent_index(tree_index: u64) -> u64 { 147 | for i in 0..62 { 148 | // find lowest-significant zero bit 149 | if (tree_index & (1 << i)) == 0 { 150 | // set that bit and clear next higher 151 | return ((tree_index | (1 << i))) & !(1 << (i + 1)); 152 | } 153 | } 154 | panic!("Parent lookup overflowed, huge index!"); 155 | } 156 | 157 | /// Calling this on a leaf node is an error, as is calling very high node numbers (> 2^62) 158 | fn tree_child_indices(tree_index: u64) -> Result<(u64, u64)> { 159 | if tree_index % 2 == 0 { 160 | bail!("Leaf tree nodes have no children"); 161 | } 162 | for i in 0..62 { 163 | // find lowest-significant zero bit... 164 | if (tree_index & (1 << i)) == 0 { 165 | // larger child has this bit high, next lower bit cleared 166 | let right = ((tree_index | (1 << i))) & !(1 << (i - 1)); 167 | // smaller child has next lower bit cleared 168 | let left = tree_index & !(1 << (i - 1)); 169 | assert!(left < right); 170 | return Ok((left, right)); 171 | } 172 | } 173 | bail!("Child lookup overflowed, huge index!"); 174 | } 175 | } 176 | 177 | #[test] 178 | fn test_tree_root_nodes() { 179 | assert_eq!(HyperRegister::tree_root_nodes(0), vec![]); 180 | assert_eq!(HyperRegister::tree_root_nodes(1), vec![0]); 181 | assert_eq!(HyperRegister::tree_root_nodes(2), vec![1]); 182 | assert_eq!(HyperRegister::tree_root_nodes(3), vec![1, 4]); 183 | assert_eq!(HyperRegister::tree_root_nodes(4), vec![3]); 184 | assert_eq!(HyperRegister::tree_root_nodes(5), vec![3, 8]); 185 | assert_eq!(HyperRegister::tree_root_nodes(6), vec![3, 9]); 186 | assert_eq!(HyperRegister::tree_root_nodes(7), vec![3, 9, 12]); 187 | assert_eq!(HyperRegister::tree_root_nodes(8), vec![7]); 188 | } 189 | 190 | #[test] 191 | fn test_tree_parent_index() { 192 | assert_eq!(HyperRegister::tree_parent_index(0), 1); 193 | assert_eq!(HyperRegister::tree_parent_index(1), 3); 194 | assert_eq!(HyperRegister::tree_parent_index(2), 1); 195 | assert_eq!(HyperRegister::tree_parent_index(3), 7); 196 | assert_eq!(HyperRegister::tree_parent_index(4), 5); 197 | assert_eq!(HyperRegister::tree_parent_index(5), 3); 198 | assert_eq!(HyperRegister::tree_parent_index(6), 5); 199 | assert_eq!(HyperRegister::tree_parent_index(7), 15); 200 | assert_eq!(HyperRegister::tree_parent_index(8), 9); 201 | assert_eq!(HyperRegister::tree_parent_index(9), 11); 202 | assert_eq!(HyperRegister::tree_parent_index(21), 19); 203 | assert_eq!(HyperRegister::tree_parent_index(22), 21); 204 | } 205 | 206 | #[test] 207 | fn test_tree_child_indices() { 208 | assert!(HyperRegister::tree_child_indices(0).is_err()); 209 | assert!(HyperRegister::tree_child_indices(1024).is_err()); 210 | assert_eq!(HyperRegister::tree_child_indices(1).unwrap(), (0, 2)); 211 | assert_eq!(HyperRegister::tree_child_indices(3).unwrap(), (1, 5)); 212 | assert_eq!(HyperRegister::tree_child_indices(5).unwrap(), (4, 6)); 213 | assert_eq!(HyperRegister::tree_child_indices(7).unwrap(), (3, 11)); 214 | assert_eq!(HyperRegister::tree_child_indices(9).unwrap(), (8, 10)); 215 | assert_eq!(HyperRegister::tree_child_indices(11).unwrap(), (9, 13)); 216 | assert_eq!(HyperRegister::tree_child_indices(13).unwrap(), (12, 14)); 217 | assert_eq!(HyperRegister::tree_child_indices(15).unwrap(), (7, 23)); 218 | assert_eq!(HyperRegister::tree_child_indices(19).unwrap(), (17, 21)); 219 | } 220 | 221 | /// Implementation of HyperRegister using a local directory of SLEEP files 222 | #[derive(Debug)] 223 | pub struct SleepDirRegister { 224 | tree_sleep: SleepFile, 225 | sign_sleep: SleepFile, 226 | bitfield_sleep: SleepFile, 227 | data_file: Option, 228 | // Except, these should be Ed25519 keys, not bytes 229 | pub_key: Vec, 230 | secret_key: Option>, 231 | path: PathBuf, 232 | prefix: String, 233 | } 234 | 235 | fn read_key_file(path: &Path, is_secret: bool) -> Result> { 236 | let expected = if is_secret { 64 } else { 32 }; 237 | let mut key = vec![]; 238 | let mut key_file = OpenOptions::new().read(true).write(false).open(path)?; 239 | key_file.read_to_end(&mut key)?; 240 | if key.len() != expected { 241 | bail!( 242 | "Bad key file (len {} != {}): {}", 243 | key.len(), 244 | expected, 245 | path.display() 246 | ); 247 | } 248 | Ok(key) 249 | } 250 | 251 | fn write_key_file(path: &Path, key: &[u8], is_secret: bool) -> Result<()> { 252 | let expected = if is_secret { 64 } else { 32 }; 253 | if key.len() != expected { 254 | bail!( 255 | "Bad key file (len {} != {}): {}", 256 | key.len(), 257 | expected, 258 | path.display() 259 | ); 260 | } 261 | let mut key_file = OpenOptions::new().write(true).create_new(true).open(path)?; 262 | key_file.write_all(&key)?; 263 | Ok(()) 264 | } 265 | 266 | impl SleepDirRegister { 267 | pub fn open(directory: &Path, prefix: &str, writable: bool) -> Result { 268 | // read public key from disk 269 | let pub_key: Vec = read_key_file( 270 | &directory.join(Path::new(&(prefix.to_owned() + ".key"))), 271 | false, 272 | )?; 273 | let mut secret_key = None; 274 | if writable { 275 | secret_key = Some(read_key_file( 276 | &directory.join(Path::new(&(prefix.to_owned() + ".secret_key"))), 277 | true, 278 | )?); 279 | } 280 | let data_path = &directory.join(Path::new(&(prefix.to_owned() + ".data"))); 281 | let data_file = if data_path.is_file() { 282 | Some(OpenOptions::new() 283 | .read(true) 284 | .write(writable) 285 | .open(data_path)?) 286 | } else { 287 | warn!("SleepDirRegister data file not found: {}", data_path.display()); 288 | None 289 | }; 290 | let tree_sleep = SleepFile::open( 291 | &directory.join(Path::new(&(prefix.to_owned() + ".tree"))), 292 | writable, 293 | )?; 294 | let sign_sleep = SleepFile::open( 295 | &directory.join(Path::new(&(prefix.to_owned() + ".signatures"))), 296 | writable, 297 | )?; 298 | let bitfield_sleep = SleepFile::open( 299 | &directory.join(Path::new(&(prefix.to_owned() + ".bitfield"))), 300 | writable, 301 | )?; 302 | let mut sf = SleepDirRegister { 303 | tree_sleep, 304 | sign_sleep, 305 | bitfield_sleep, 306 | data_file, 307 | pub_key, 308 | secret_key, 309 | path: directory.to_path_buf(), 310 | prefix: prefix.to_string(), 311 | }; 312 | sf.check()?; 313 | Ok(sf) 314 | } 315 | 316 | /// In addition to what one would expect, also creates an Ed25519 key-pair using OsRng 317 | pub fn create(directory: &Path, prefix: &str) -> Result { 318 | let mut rand_seed = vec![0; 32]; 319 | let mut rng = OsRng::new()?; 320 | rng.fill_bytes(&mut rand_seed); 321 | let (secret_key, pub_key) = ed25519::keypair(&rand_seed); 322 | write_key_file( 323 | &directory.join(Path::new(&(prefix.to_owned() + ".key"))), 324 | &pub_key, 325 | false, 326 | )?; 327 | write_key_file( 328 | &directory.join(Path::new(&(prefix.to_owned() + ".secret_key"))), 329 | &secret_key, 330 | true, 331 | )?; 332 | let data_file = OpenOptions::new() 333 | .read(true) 334 | .write(true) 335 | .create_new(true) 336 | .open(directory.join(Path::new(&(prefix.to_owned() + ".data"))))?; 337 | let tree_sleep = SleepFile::create( 338 | &directory.join(Path::new(&(prefix.to_owned() + ".tree"))), 339 | 0x05025702, 340 | 40, 341 | Some("BLAKE2b".to_string()), 342 | )?; 343 | let sign_sleep = SleepFile::create( 344 | &directory.join(Path::new(&(prefix.to_owned() + ".signatures"))), 345 | 0x05025701, 346 | 64, 347 | Some("Ed25519".to_string()), 348 | )?; 349 | let bitfield_sleep = SleepFile::create( 350 | &directory.join(Path::new(&(prefix.to_owned() + ".bitfield"))), 351 | 0x05025700, 352 | 3328, 353 | None, 354 | )?; 355 | let mut sf = SleepDirRegister { 356 | tree_sleep, 357 | sign_sleep, 358 | bitfield_sleep, 359 | data_file: Some(data_file), 360 | pub_key: pub_key.to_vec(), 361 | secret_key: Some(secret_key.to_vec()), 362 | path: directory.to_path_buf(), 363 | prefix: prefix.to_string(), 364 | }; 365 | sf.check()?; 366 | Ok(sf) 367 | } 368 | 369 | pub fn discovery_key(&self) -> Vec { 370 | make_discovery_key(&self.pub_key) 371 | } 372 | } 373 | 374 | impl HyperRegister for SleepDirRegister { 375 | /// TODO: this version only works for "dense" registers: it just checks if the index is in the 376 | /// total length, instead of using the bitfield. 377 | fn has(&self, entry_index: u64) -> Result { 378 | return Ok(entry_index < self.len()?); 379 | } 380 | 381 | fn has_all(&self) -> Result { 382 | self.has_range(0, self.len()?) 383 | } 384 | 385 | fn has_range(&self, start: u64, end: u64) -> Result { 386 | // This function is un-motivated and could be removed 387 | assert!(end > start); 388 | for i in start..end { 389 | if !self.has(i)? { 390 | return Ok(false); 391 | } 392 | } 393 | Ok(true) 394 | } 395 | 396 | fn get_data_entry(&mut self, index: u64) -> Result> { 397 | // Get metadata about chunk (offset and length) 398 | let offset = HyperRegister::get_data_offset(self, index)?; 399 | 400 | // Do we even have this chunk? 401 | if !self.has(index)? { 402 | bail!("Don't have that chunk"); 403 | } 404 | 405 | let data_file = if let Some(ref mut df) = self.data_file { 406 | df 407 | } else { 408 | bail!("No data file in this register (dir={} prefix={})", self.path.display(), self.prefix); 409 | }; 410 | let leaf = self.tree_sleep.read(index * 2)?; 411 | let data_len = u64::from_be(FixedInt::decode_fixed(&leaf[32..40])); 412 | // avoid foot-gun in development: cap at ~1 billion bytes 413 | assert!(data_len < 2u64.pow(29)); 414 | 415 | // Read chunk 416 | let mut data = vec![0; data_len as usize]; 417 | let got = data_file.read_at(&mut data, offset)?; 418 | if got != data.len() { 419 | bail!("Short file read"); 420 | } 421 | 422 | // TODO: check the hash? separate function? 423 | Ok(data) 424 | } 425 | 426 | fn get_tree_entry(&mut self, tree_index: u64) -> Result> { 427 | self.tree_sleep.read(tree_index) 428 | } 429 | 430 | fn append(&mut self, data: &[u8]) -> Result { 431 | if !self.data_file.is_some() { 432 | bail!("No data file in this register"); 433 | }; 434 | 435 | let index = self.len()?; 436 | // 1. Hash data chunk 437 | let leaf_hash = HyperRegister::hash_leaf(data); 438 | 439 | // 2. Append data to data file 440 | if let Some(ref mut df) = self.data_file { 441 | df.seek(SeekFrom::End(0))?; 442 | df.write_all(data)?; 443 | df.sync_data()?; 444 | } 445 | 446 | // 3. Add hash to tree file, update merkel tree 447 | self.tree_sleep.write(index * 2, &leaf_hash)?; 448 | let mut parent = HyperRegister::tree_parent_index(index * 2); 449 | while parent < index * 2 { 450 | let (left, right) = HyperRegister::tree_child_indices(parent)?; 451 | let (left, right) = (self.tree_sleep.read(left)?, self.tree_sleep.read(right)?); 452 | let parent_hash = HyperRegister::hash_parent(&left[0..40], &right[0..40]); 453 | self.tree_sleep.write(parent, &parent_hash[0..40])?; 454 | parent = HyperRegister::tree_parent_index(parent); 455 | } 456 | 457 | // 4. Add signature to signature file 458 | let root_hash = HyperRegister::hash_roots(self, index)?; 459 | let root_sig = ed25519::signature(&root_hash, &self.secret_key.clone().unwrap()); 460 | self.sign_sleep.append(&root_sig)?; 461 | 462 | // 5. Update bitfile 463 | Ok(index) 464 | } 465 | 466 | fn len(&self) -> Result { 467 | // Length in entry count. 468 | let tree_len = self.tree_sleep.len()?; 469 | if tree_len == 0 { 470 | Ok(0) 471 | } else if tree_len % 2 != 1 { 472 | bail!("Even number of tree file SLEEP entries"); 473 | } else { 474 | Ok((self.tree_sleep.len()? / 2) + 1) 475 | } 476 | } 477 | 478 | fn len_bytes(&mut self) -> Result { 479 | // TODO: this is a naive (linear) implementation 480 | // log(N) would go up previous parent nodes (eg, use tree_root_nodes()) 481 | let mut sum: u64 = 0; 482 | for i in 0..self.len()? { 483 | let leaf = self.get_tree_entry(i * 2)?; 484 | sum += u64::from_be(FixedInt::decode_fixed(&leaf[32..40])); 485 | } 486 | Ok(sum) 487 | } 488 | 489 | fn verify(&mut self) -> Result<()> { 490 | for i in 0..self.len()? { 491 | 492 | if let Some(_) = self.data_file { 493 | // 1. Read and hash data 494 | let data_chunk = self.get_data_entry(i)?; 495 | let leaf_recalc = HyperRegister::hash_leaf(&data_chunk); 496 | 497 | // 2. Check tree leaf hash for this chunk 498 | let leaf = self.get_tree_entry(i * 2)?; 499 | if leaf.to_vec() != leaf_recalc.to_vec() { 500 | bail!("Data chunk {} failed verification (leaf hash)", i); 501 | } 502 | } else { 503 | warn!("No simple datafile, can't verify hashes"); 504 | } 505 | 506 | // 3. Recurse up parents, hashing all parents 507 | let rehash = HyperRegister::hash_roots(self, i)?; 508 | 509 | // 4. Read and verify signature in file 510 | let sig = self.sign_sleep.read(i)?; 511 | if !ed25519::verify(&rehash, &self.pub_key, &sig) { 512 | bail!("Failed to verify signature for chunk {}", i) 513 | } 514 | } 515 | Ok(()) 516 | } 517 | 518 | fn check(&mut self) -> Result<()> { 519 | let sign_len = self.sign_sleep.len()?; 520 | let tree_len = self.tree_sleep.len()?; 521 | if (tree_len == 0) && (sign_len == 0) { 522 | return Ok(()); 523 | } 524 | if tree_len != (sign_len * 2) - 1 { 525 | bail!("Inconsistent SLEEP signature/tree file sizes"); 526 | } 527 | let computed = self.len_bytes()?; 528 | if let Some(ref df) = self.data_file { 529 | let file_size = df.metadata()?.len(); 530 | if file_size != computed { 531 | bail!("Computed vs. data file size mismatch ({} != {}; path={} prefix={})", 532 | computed, file_size, self.path.display(), self.prefix); 533 | } 534 | } 535 | Ok(()) 536 | } 537 | 538 | /// Checks if we have the secret key (such that we can append to this register) 539 | fn writable(&self) -> bool { 540 | return self.secret_key.is_some(); 541 | } 542 | } 543 | 544 | #[test] 545 | fn test_sdr_open() { 546 | 547 | let mut sdr = 548 | SleepDirRegister::open(Path::new("test-data/dat/simple/.dat/"), "metadata", false).unwrap(); 549 | 550 | // Values from 'dat log' 551 | assert!(sdr.check().is_ok()); 552 | assert!(sdr.verify().is_ok()); 553 | assert_eq!(sdr.len().unwrap(), 3); 554 | assert_eq!(sdr.len_bytes().unwrap(), 145); 555 | 556 | let mut sdr = 557 | SleepDirRegister::open(Path::new("test-data/dat/simple/.dat/"), "content", false).unwrap(); 558 | 559 | // Values from 'dat log' 560 | assert!(sdr.check().is_ok()); 561 | assert!(sdr.verify().is_ok()); 562 | assert_eq!(sdr.len().unwrap(), 2); 563 | assert_eq!(sdr.len_bytes().unwrap(), 204); 564 | 565 | let mut sdr = 566 | SleepDirRegister::open(Path::new("test-data/dat/alphabet/.dat/"), "metadata", false).unwrap(); 567 | 568 | // Values from 'dat log' 569 | assert!(sdr.check().is_ok()); 570 | assert!(sdr.verify().is_ok()); 571 | assert_eq!(sdr.len().unwrap(), 7); 572 | assert_eq!(sdr.len_bytes().unwrap(), 307); 573 | 574 | let mut sdr = 575 | SleepDirRegister::open(Path::new("test-data/dat/alphabet/.dat/"), "content", false).unwrap(); 576 | 577 | // Values from 'dat log' 578 | assert!(sdr.check().is_ok()); 579 | assert!(sdr.verify().is_ok()); 580 | assert_eq!(sdr.len().unwrap(), 6); 581 | assert_eq!(sdr.len_bytes().unwrap(), 6); 582 | 583 | } 584 | 585 | #[test] 586 | fn test_sdr_create() { 587 | use tempdir::TempDir; 588 | let tmp_dir = TempDir::new("geniza-test").unwrap(); 589 | let mut sdr = SleepDirRegister::create(tmp_dir.path(), "dummy").unwrap(); 590 | 591 | assert_eq!(sdr.len().unwrap(), 0); 592 | assert_eq!(sdr.len_bytes().unwrap(), 0); 593 | } 594 | 595 | #[test] 596 | fn test_sdr_append() { 597 | use tempdir::TempDir; 598 | let tmp_dir = TempDir::new("geniza-test").unwrap(); 599 | let mut sdr = SleepDirRegister::create(tmp_dir.path(), "dummy").unwrap(); 600 | 601 | let index = sdr.append("hello world!".as_bytes()).unwrap(); 602 | assert_eq!(index, 0); 603 | assert!(sdr.check().is_ok()); 604 | assert!(sdr.verify().is_ok()); 605 | assert_eq!(sdr.len().unwrap(), 1); 606 | assert_eq!(sdr.len_bytes().unwrap(), 12); 607 | let count = 100; // TODO: make this >1000 when things are faster 608 | for i in 0..count { 609 | let index = sdr.append(&[1, 2, 3, 4, 5]).unwrap(); 610 | assert_eq!(index, i+1); 611 | } 612 | assert!(sdr.check().is_ok()); 613 | assert!(sdr.verify().is_ok()); 614 | assert_eq!(sdr.len().unwrap(), 1 + count); 615 | assert_eq!(sdr.len_bytes().unwrap(), 12 + (count * 5)); 616 | } 617 | 618 | #[test] 619 | fn test_sdr_has() { 620 | use tempdir::TempDir; 621 | let tmp_dir = TempDir::new("geniza-test").unwrap(); 622 | let mut sdr = SleepDirRegister::create(tmp_dir.path(), "dummy").unwrap(); 623 | 624 | sdr.append("hello world!".as_bytes()).unwrap(); 625 | assert!(sdr.check().is_ok()); 626 | assert_eq!(sdr.has_all().unwrap(), true); 627 | assert_eq!(sdr.has(0).unwrap(), true); 628 | assert_eq!(sdr.has(40).unwrap(), false); 629 | } 630 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "addr2line" 7 | version = "0.17.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" 10 | dependencies = [ 11 | "gimli", 12 | ] 13 | 14 | [[package]] 15 | name = "adler" 16 | version = "1.0.2" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" 19 | 20 | [[package]] 21 | name = "aho-corasick" 22 | version = "0.5.3" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "ca972c2ea5f742bfce5687b9aef75506a764f61d37f8f649047846a9686ddb66" 25 | dependencies = [ 26 | "memchr 0.1.11", 27 | ] 28 | 29 | [[package]] 30 | name = "ansi_term" 31 | version = "0.12.1" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" 34 | dependencies = [ 35 | "winapi 0.3.9", 36 | ] 37 | 38 | [[package]] 39 | name = "assert_cli" 40 | version = "0.5.4" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "72342c21057a3cb5f7c2d849bf7999a83795434dd36d74fa8c24680581bd1930" 43 | dependencies = [ 44 | "colored", 45 | "difference", 46 | "environment", 47 | "error-chain 0.11.0", 48 | "serde_json", 49 | "skeptic", 50 | ] 51 | 52 | [[package]] 53 | name = "atty" 54 | version = "0.2.14" 55 | source = "registry+https://github.com/rust-lang/crates.io-index" 56 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 57 | dependencies = [ 58 | "hermit-abi", 59 | "libc", 60 | "winapi 0.3.9", 61 | ] 62 | 63 | [[package]] 64 | name = "backtrace" 65 | version = "0.3.66" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7" 68 | dependencies = [ 69 | "addr2line", 70 | "cc", 71 | "cfg-if", 72 | "libc", 73 | "miniz_oxide", 74 | "object", 75 | "rustc-demangle", 76 | ] 77 | 78 | [[package]] 79 | name = "bit-set" 80 | version = "0.4.0" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | checksum = "d9bf6104718e80d7b26a68fdbacff3481cfc05df670821affc7e9cbc1884400c" 83 | dependencies = [ 84 | "bit-vec", 85 | ] 86 | 87 | [[package]] 88 | name = "bit-vec" 89 | version = "0.4.4" 90 | source = "registry+https://github.com/rust-lang/crates.io-index" 91 | checksum = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f" 92 | 93 | [[package]] 94 | name = "bit_field" 95 | version = "0.9.0" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | checksum = "ed8765909f9009617974ab6b7d332625b320b33c326b1e9321382ef1999b5d56" 98 | 99 | [[package]] 100 | name = "bitflags" 101 | version = "1.3.2" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 104 | 105 | [[package]] 106 | name = "bytecount" 107 | version = "0.6.3" 108 | source = "registry+https://github.com/rust-lang/crates.io-index" 109 | checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c" 110 | 111 | [[package]] 112 | name = "camino" 113 | version = "1.1.1" 114 | source = "registry+https://github.com/rust-lang/crates.io-index" 115 | checksum = "88ad0e1e3e88dd237a156ab9f571021b8a158caa0ae44b1968a241efb5144c1e" 116 | dependencies = [ 117 | "serde", 118 | ] 119 | 120 | [[package]] 121 | name = "cargo-platform" 122 | version = "0.1.2" 123 | source = "registry+https://github.com/rust-lang/crates.io-index" 124 | checksum = "cbdb825da8a5df079a43676dbe042702f1707b1109f713a01420fbb4cc71fa27" 125 | dependencies = [ 126 | "serde", 127 | ] 128 | 129 | [[package]] 130 | name = "cargo_metadata" 131 | version = "0.14.2" 132 | source = "registry+https://github.com/rust-lang/crates.io-index" 133 | checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa" 134 | dependencies = [ 135 | "camino", 136 | "cargo-platform", 137 | "semver", 138 | "serde", 139 | "serde_json", 140 | ] 141 | 142 | [[package]] 143 | name = "cc" 144 | version = "1.0.73" 145 | source = "registry+https://github.com/rust-lang/crates.io-index" 146 | checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" 147 | 148 | [[package]] 149 | name = "cfg-if" 150 | version = "1.0.0" 151 | source = "registry+https://github.com/rust-lang/crates.io-index" 152 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 153 | 154 | [[package]] 155 | name = "chan" 156 | version = "0.1.23" 157 | source = "registry+https://github.com/rust-lang/crates.io-index" 158 | checksum = "d14956a3dae065ffaa0d92ece848ab4ced88d32361e7fdfbfd653a5c454a1ed8" 159 | dependencies = [ 160 | "rand 0.3.23", 161 | ] 162 | 163 | [[package]] 164 | name = "chan-signal" 165 | version = "0.3.3" 166 | source = "registry+https://github.com/rust-lang/crates.io-index" 167 | checksum = "5b829e3f5432da0cc46577d89fc88c937e78052e6735fb47ce0213b0db120b01" 168 | dependencies = [ 169 | "bit-set", 170 | "chan", 171 | "lazy_static 0.2.11", 172 | "libc", 173 | ] 174 | 175 | [[package]] 176 | name = "clap" 177 | version = "2.34.0" 178 | source = "registry+https://github.com/rust-lang/crates.io-index" 179 | checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" 180 | dependencies = [ 181 | "ansi_term", 182 | "atty", 183 | "bitflags", 184 | "strsim", 185 | "textwrap", 186 | "unicode-width", 187 | "vec_map", 188 | ] 189 | 190 | [[package]] 191 | name = "colored" 192 | version = "1.9.3" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | checksum = "f4ffc801dacf156c5854b9df4f425a626539c3a6ef7893cc0c5084a23f0b6c59" 195 | dependencies = [ 196 | "atty", 197 | "lazy_static 1.4.0", 198 | "winapi 0.3.9", 199 | ] 200 | 201 | [[package]] 202 | name = "data-encoding" 203 | version = "2.3.2" 204 | source = "registry+https://github.com/rust-lang/crates.io-index" 205 | checksum = "3ee2393c4a91429dffb4bedf19f4d6abf27d8a732c8ce4980305d782e5426d57" 206 | 207 | [[package]] 208 | name = "difference" 209 | version = "1.0.0" 210 | source = "registry+https://github.com/rust-lang/crates.io-index" 211 | checksum = "b3304d19798a8e067e48d8e69b2c37f0b5e9b4e462504ad9e27e9f3fce02bba8" 212 | 213 | [[package]] 214 | name = "env_logger" 215 | version = "0.3.5" 216 | source = "registry+https://github.com/rust-lang/crates.io-index" 217 | checksum = "15abd780e45b3ea4f76b4e9a26ff4843258dd8a3eed2775a0e7368c2e7936c2f" 218 | dependencies = [ 219 | "log 0.3.9", 220 | "regex", 221 | ] 222 | 223 | [[package]] 224 | name = "environment" 225 | version = "0.1.1" 226 | source = "registry+https://github.com/rust-lang/crates.io-index" 227 | checksum = "1f4b14e20978669064c33b4c1e0fb4083412e40fe56cbea2eae80fd7591503ee" 228 | 229 | [[package]] 230 | name = "error-chain" 231 | version = "0.7.2" 232 | source = "registry+https://github.com/rust-lang/crates.io-index" 233 | checksum = "318cb3c71ee4cdea69fdc9e15c173b245ed6063e1709029e8fd32525a881120f" 234 | dependencies = [ 235 | "backtrace", 236 | ] 237 | 238 | [[package]] 239 | name = "error-chain" 240 | version = "0.11.0" 241 | source = "registry+https://github.com/rust-lang/crates.io-index" 242 | checksum = "ff511d5dc435d703f4971bc399647c9bc38e20cb41452e3b9feb4765419ed3f3" 243 | dependencies = [ 244 | "backtrace", 245 | ] 246 | 247 | [[package]] 248 | name = "error-chain" 249 | version = "0.12.4" 250 | source = "registry+https://github.com/rust-lang/crates.io-index" 251 | checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" 252 | dependencies = [ 253 | "version_check", 254 | ] 255 | 256 | [[package]] 257 | name = "fastrand" 258 | version = "1.8.0" 259 | source = "registry+https://github.com/rust-lang/crates.io-index" 260 | checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" 261 | dependencies = [ 262 | "instant", 263 | ] 264 | 265 | [[package]] 266 | name = "fuchsia-cprng" 267 | version = "0.1.1" 268 | source = "registry+https://github.com/rust-lang/crates.io-index" 269 | checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" 270 | 271 | [[package]] 272 | name = "gcc" 273 | version = "0.3.55" 274 | source = "registry+https://github.com/rust-lang/crates.io-index" 275 | checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" 276 | 277 | [[package]] 278 | name = "geniza" 279 | version = "0.1.0" 280 | dependencies = [ 281 | "assert_cli", 282 | "bit-vec", 283 | "bit_field", 284 | "chan", 285 | "chan-signal", 286 | "clap", 287 | "data-encoding", 288 | "env_logger", 289 | "error-chain 0.7.2", 290 | "integer-encoding", 291 | "log 0.3.9", 292 | "protobuf", 293 | "rand 0.3.23", 294 | "resolve", 295 | "rust-crypto", 296 | "sodiumoxide", 297 | "tempdir", 298 | ] 299 | 300 | [[package]] 301 | name = "gimli" 302 | version = "0.26.2" 303 | source = "registry+https://github.com/rust-lang/crates.io-index" 304 | checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" 305 | 306 | [[package]] 307 | name = "glob" 308 | version = "0.3.0" 309 | source = "registry+https://github.com/rust-lang/crates.io-index" 310 | checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" 311 | 312 | [[package]] 313 | name = "hermit-abi" 314 | version = "0.1.19" 315 | source = "registry+https://github.com/rust-lang/crates.io-index" 316 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 317 | dependencies = [ 318 | "libc", 319 | ] 320 | 321 | [[package]] 322 | name = "idna" 323 | version = "0.1.5" 324 | source = "registry+https://github.com/rust-lang/crates.io-index" 325 | checksum = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" 326 | dependencies = [ 327 | "matches", 328 | "unicode-bidi", 329 | "unicode-normalization", 330 | ] 331 | 332 | [[package]] 333 | name = "instant" 334 | version = "0.1.12" 335 | source = "registry+https://github.com/rust-lang/crates.io-index" 336 | checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" 337 | dependencies = [ 338 | "cfg-if", 339 | ] 340 | 341 | [[package]] 342 | name = "integer-encoding" 343 | version = "1.1.7" 344 | source = "registry+https://github.com/rust-lang/crates.io-index" 345 | checksum = "48dc51180a9b377fd75814d0cc02199c20f8e99433d6762f650d39cdbbd3b56f" 346 | 347 | [[package]] 348 | name = "itoa" 349 | version = "1.0.3" 350 | source = "registry+https://github.com/rust-lang/crates.io-index" 351 | checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" 352 | 353 | [[package]] 354 | name = "kernel32-sys" 355 | version = "0.2.2" 356 | source = "registry+https://github.com/rust-lang/crates.io-index" 357 | checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" 358 | dependencies = [ 359 | "winapi 0.2.8", 360 | "winapi-build", 361 | ] 362 | 363 | [[package]] 364 | name = "lazy_static" 365 | version = "0.2.11" 366 | source = "registry+https://github.com/rust-lang/crates.io-index" 367 | checksum = "76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73" 368 | 369 | [[package]] 370 | name = "lazy_static" 371 | version = "1.4.0" 372 | source = "registry+https://github.com/rust-lang/crates.io-index" 373 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 374 | 375 | [[package]] 376 | name = "libc" 377 | version = "0.2.132" 378 | source = "registry+https://github.com/rust-lang/crates.io-index" 379 | checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5" 380 | 381 | [[package]] 382 | name = "libsodium-sys" 383 | version = "0.0.16" 384 | source = "registry+https://github.com/rust-lang/crates.io-index" 385 | checksum = "fcbd1beeed8d44caa8a669ebaa697c313976e242c03cc9fb23d88bf1656f5542" 386 | dependencies = [ 387 | "libc", 388 | "pkg-config", 389 | ] 390 | 391 | [[package]] 392 | name = "log" 393 | version = "0.3.9" 394 | source = "registry+https://github.com/rust-lang/crates.io-index" 395 | checksum = "e19e8d5c34a3e0e2223db8e060f9e8264aeeb5c5fc64a4ee9965c062211c024b" 396 | dependencies = [ 397 | "log 0.4.17", 398 | ] 399 | 400 | [[package]] 401 | name = "log" 402 | version = "0.4.17" 403 | source = "registry+https://github.com/rust-lang/crates.io-index" 404 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 405 | dependencies = [ 406 | "cfg-if", 407 | ] 408 | 409 | [[package]] 410 | name = "matches" 411 | version = "0.1.9" 412 | source = "registry+https://github.com/rust-lang/crates.io-index" 413 | checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" 414 | 415 | [[package]] 416 | name = "memchr" 417 | version = "0.1.11" 418 | source = "registry+https://github.com/rust-lang/crates.io-index" 419 | checksum = "d8b629fb514376c675b98c1421e80b151d3817ac42d7c667717d282761418d20" 420 | dependencies = [ 421 | "libc", 422 | ] 423 | 424 | [[package]] 425 | name = "memchr" 426 | version = "2.5.0" 427 | source = "registry+https://github.com/rust-lang/crates.io-index" 428 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 429 | 430 | [[package]] 431 | name = "miniz_oxide" 432 | version = "0.5.4" 433 | source = "registry+https://github.com/rust-lang/crates.io-index" 434 | checksum = "96590ba8f175222643a85693f33d26e9c8a015f599c216509b1a6894af675d34" 435 | dependencies = [ 436 | "adler", 437 | ] 438 | 439 | [[package]] 440 | name = "object" 441 | version = "0.29.0" 442 | source = "registry+https://github.com/rust-lang/crates.io-index" 443 | checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" 444 | dependencies = [ 445 | "memchr 2.5.0", 446 | ] 447 | 448 | [[package]] 449 | name = "pkg-config" 450 | version = "0.3.25" 451 | source = "registry+https://github.com/rust-lang/crates.io-index" 452 | checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" 453 | 454 | [[package]] 455 | name = "proc-macro2" 456 | version = "1.0.43" 457 | source = "registry+https://github.com/rust-lang/crates.io-index" 458 | checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" 459 | dependencies = [ 460 | "unicode-ident", 461 | ] 462 | 463 | [[package]] 464 | name = "protobuf" 465 | version = "1.7.5" 466 | source = "registry+https://github.com/rust-lang/crates.io-index" 467 | checksum = "e14ccd6b79ec748412d4f2dfde1a80fa363a67def4062969f8aed3d790a30f28" 468 | 469 | [[package]] 470 | name = "pulldown-cmark" 471 | version = "0.9.2" 472 | source = "registry+https://github.com/rust-lang/crates.io-index" 473 | checksum = "2d9cc634bc78768157b5cbfe988ffcd1dcba95cd2b2f03a88316c08c6d00ed63" 474 | dependencies = [ 475 | "bitflags", 476 | "memchr 2.5.0", 477 | "unicase", 478 | ] 479 | 480 | [[package]] 481 | name = "quote" 482 | version = "1.0.21" 483 | source = "registry+https://github.com/rust-lang/crates.io-index" 484 | checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" 485 | dependencies = [ 486 | "proc-macro2", 487 | ] 488 | 489 | [[package]] 490 | name = "rand" 491 | version = "0.3.23" 492 | source = "registry+https://github.com/rust-lang/crates.io-index" 493 | checksum = "64ac302d8f83c0c1974bf758f6b041c6c8ada916fbb44a609158ca8b064cc76c" 494 | dependencies = [ 495 | "libc", 496 | "rand 0.4.6", 497 | ] 498 | 499 | [[package]] 500 | name = "rand" 501 | version = "0.4.6" 502 | source = "registry+https://github.com/rust-lang/crates.io-index" 503 | checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" 504 | dependencies = [ 505 | "fuchsia-cprng", 506 | "libc", 507 | "rand_core 0.3.1", 508 | "rdrand", 509 | "winapi 0.3.9", 510 | ] 511 | 512 | [[package]] 513 | name = "rand_core" 514 | version = "0.3.1" 515 | source = "registry+https://github.com/rust-lang/crates.io-index" 516 | checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" 517 | dependencies = [ 518 | "rand_core 0.4.2", 519 | ] 520 | 521 | [[package]] 522 | name = "rand_core" 523 | version = "0.4.2" 524 | source = "registry+https://github.com/rust-lang/crates.io-index" 525 | checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" 526 | 527 | [[package]] 528 | name = "rdrand" 529 | version = "0.4.0" 530 | source = "registry+https://github.com/rust-lang/crates.io-index" 531 | checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" 532 | dependencies = [ 533 | "rand_core 0.3.1", 534 | ] 535 | 536 | [[package]] 537 | name = "redox_syscall" 538 | version = "0.2.16" 539 | source = "registry+https://github.com/rust-lang/crates.io-index" 540 | checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" 541 | dependencies = [ 542 | "bitflags", 543 | ] 544 | 545 | [[package]] 546 | name = "regex" 547 | version = "0.1.80" 548 | source = "registry+https://github.com/rust-lang/crates.io-index" 549 | checksum = "4fd4ace6a8cf7860714a2c2280d6c1f7e6a413486c13298bbc86fd3da019402f" 550 | dependencies = [ 551 | "aho-corasick", 552 | "memchr 0.1.11", 553 | "regex-syntax", 554 | "thread_local", 555 | "utf8-ranges", 556 | ] 557 | 558 | [[package]] 559 | name = "regex-syntax" 560 | version = "0.3.9" 561 | source = "registry+https://github.com/rust-lang/crates.io-index" 562 | checksum = "f9ec002c35e86791825ed294b50008eea9ddfc8def4420124fbc6b08db834957" 563 | 564 | [[package]] 565 | name = "remove_dir_all" 566 | version = "0.5.3" 567 | source = "registry+https://github.com/rust-lang/crates.io-index" 568 | checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" 569 | dependencies = [ 570 | "winapi 0.3.9", 571 | ] 572 | 573 | [[package]] 574 | name = "resolve" 575 | version = "0.2.0" 576 | source = "registry+https://github.com/rust-lang/crates.io-index" 577 | checksum = "19526b305899bea65f26edda78a64f5313958494321ee0ab66bd94b32958614a" 578 | dependencies = [ 579 | "idna", 580 | "libc", 581 | "log 0.3.9", 582 | "rand 0.3.23", 583 | ] 584 | 585 | [[package]] 586 | name = "rust-crypto" 587 | version = "0.2.36" 588 | source = "registry+https://github.com/rust-lang/crates.io-index" 589 | checksum = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" 590 | dependencies = [ 591 | "gcc", 592 | "libc", 593 | "rand 0.3.23", 594 | "rustc-serialize", 595 | "time", 596 | ] 597 | 598 | [[package]] 599 | name = "rustc-demangle" 600 | version = "0.1.21" 601 | source = "registry+https://github.com/rust-lang/crates.io-index" 602 | checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" 603 | 604 | [[package]] 605 | name = "rustc-serialize" 606 | version = "0.3.24" 607 | source = "registry+https://github.com/rust-lang/crates.io-index" 608 | checksum = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" 609 | 610 | [[package]] 611 | name = "ryu" 612 | version = "1.0.11" 613 | source = "registry+https://github.com/rust-lang/crates.io-index" 614 | checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" 615 | 616 | [[package]] 617 | name = "same-file" 618 | version = "1.0.6" 619 | source = "registry+https://github.com/rust-lang/crates.io-index" 620 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 621 | dependencies = [ 622 | "winapi-util", 623 | ] 624 | 625 | [[package]] 626 | name = "semver" 627 | version = "1.0.13" 628 | source = "registry+https://github.com/rust-lang/crates.io-index" 629 | checksum = "93f6841e709003d68bb2deee8c343572bf446003ec20a583e76f7b15cebf3711" 630 | dependencies = [ 631 | "serde", 632 | ] 633 | 634 | [[package]] 635 | name = "serde" 636 | version = "1.0.144" 637 | source = "registry+https://github.com/rust-lang/crates.io-index" 638 | checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860" 639 | dependencies = [ 640 | "serde_derive", 641 | ] 642 | 643 | [[package]] 644 | name = "serde_derive" 645 | version = "1.0.144" 646 | source = "registry+https://github.com/rust-lang/crates.io-index" 647 | checksum = "94ed3a816fb1d101812f83e789f888322c34e291f894f19590dc310963e87a00" 648 | dependencies = [ 649 | "proc-macro2", 650 | "quote", 651 | "syn", 652 | ] 653 | 654 | [[package]] 655 | name = "serde_json" 656 | version = "1.0.85" 657 | source = "registry+https://github.com/rust-lang/crates.io-index" 658 | checksum = "e55a28e3aaef9d5ce0506d0a14dbba8054ddc7e499ef522dd8b26859ec9d4a44" 659 | dependencies = [ 660 | "itoa", 661 | "ryu", 662 | "serde", 663 | ] 664 | 665 | [[package]] 666 | name = "skeptic" 667 | version = "0.13.7" 668 | source = "registry+https://github.com/rust-lang/crates.io-index" 669 | checksum = "16d23b015676c90a0f01c197bfdc786c20342c73a0afdda9025adb0bc42940a8" 670 | dependencies = [ 671 | "bytecount", 672 | "cargo_metadata", 673 | "error-chain 0.12.4", 674 | "glob", 675 | "pulldown-cmark", 676 | "tempfile", 677 | "walkdir", 678 | ] 679 | 680 | [[package]] 681 | name = "sodiumoxide" 682 | version = "0.0.16" 683 | source = "registry+https://github.com/rust-lang/crates.io-index" 684 | checksum = "eb5cb2f14f9a51352ad65e59257a0a9459d5a36a3615f3d53a974c82fdaaa00a" 685 | dependencies = [ 686 | "libc", 687 | "libsodium-sys", 688 | "serde", 689 | ] 690 | 691 | [[package]] 692 | name = "strsim" 693 | version = "0.8.0" 694 | source = "registry+https://github.com/rust-lang/crates.io-index" 695 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 696 | 697 | [[package]] 698 | name = "syn" 699 | version = "1.0.99" 700 | source = "registry+https://github.com/rust-lang/crates.io-index" 701 | checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" 702 | dependencies = [ 703 | "proc-macro2", 704 | "quote", 705 | "unicode-ident", 706 | ] 707 | 708 | [[package]] 709 | name = "tempdir" 710 | version = "0.3.7" 711 | source = "registry+https://github.com/rust-lang/crates.io-index" 712 | checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8" 713 | dependencies = [ 714 | "rand 0.4.6", 715 | "remove_dir_all", 716 | ] 717 | 718 | [[package]] 719 | name = "tempfile" 720 | version = "3.3.0" 721 | source = "registry+https://github.com/rust-lang/crates.io-index" 722 | checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" 723 | dependencies = [ 724 | "cfg-if", 725 | "fastrand", 726 | "libc", 727 | "redox_syscall", 728 | "remove_dir_all", 729 | "winapi 0.3.9", 730 | ] 731 | 732 | [[package]] 733 | name = "textwrap" 734 | version = "0.11.0" 735 | source = "registry+https://github.com/rust-lang/crates.io-index" 736 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 737 | dependencies = [ 738 | "unicode-width", 739 | ] 740 | 741 | [[package]] 742 | name = "thread-id" 743 | version = "2.0.0" 744 | source = "registry+https://github.com/rust-lang/crates.io-index" 745 | checksum = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" 746 | dependencies = [ 747 | "kernel32-sys", 748 | "libc", 749 | ] 750 | 751 | [[package]] 752 | name = "thread_local" 753 | version = "0.2.7" 754 | source = "registry+https://github.com/rust-lang/crates.io-index" 755 | checksum = "8576dbbfcaef9641452d5cf0df9b0e7eeab7694956dd33bb61515fb8f18cfdd5" 756 | dependencies = [ 757 | "thread-id", 758 | ] 759 | 760 | [[package]] 761 | name = "time" 762 | version = "0.1.44" 763 | source = "registry+https://github.com/rust-lang/crates.io-index" 764 | checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" 765 | dependencies = [ 766 | "libc", 767 | "wasi", 768 | "winapi 0.3.9", 769 | ] 770 | 771 | [[package]] 772 | name = "tinyvec" 773 | version = "1.6.0" 774 | source = "registry+https://github.com/rust-lang/crates.io-index" 775 | checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" 776 | dependencies = [ 777 | "tinyvec_macros", 778 | ] 779 | 780 | [[package]] 781 | name = "tinyvec_macros" 782 | version = "0.1.0" 783 | source = "registry+https://github.com/rust-lang/crates.io-index" 784 | checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" 785 | 786 | [[package]] 787 | name = "unicase" 788 | version = "2.6.0" 789 | source = "registry+https://github.com/rust-lang/crates.io-index" 790 | checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" 791 | dependencies = [ 792 | "version_check", 793 | ] 794 | 795 | [[package]] 796 | name = "unicode-bidi" 797 | version = "0.3.8" 798 | source = "registry+https://github.com/rust-lang/crates.io-index" 799 | checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" 800 | 801 | [[package]] 802 | name = "unicode-ident" 803 | version = "1.0.3" 804 | source = "registry+https://github.com/rust-lang/crates.io-index" 805 | checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" 806 | 807 | [[package]] 808 | name = "unicode-normalization" 809 | version = "0.1.21" 810 | source = "registry+https://github.com/rust-lang/crates.io-index" 811 | checksum = "854cbdc4f7bc6ae19c820d44abdc3277ac3e1b2b93db20a636825d9322fb60e6" 812 | dependencies = [ 813 | "tinyvec", 814 | ] 815 | 816 | [[package]] 817 | name = "unicode-width" 818 | version = "0.1.9" 819 | source = "registry+https://github.com/rust-lang/crates.io-index" 820 | checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" 821 | 822 | [[package]] 823 | name = "utf8-ranges" 824 | version = "0.1.3" 825 | source = "registry+https://github.com/rust-lang/crates.io-index" 826 | checksum = "a1ca13c08c41c9c3e04224ed9ff80461d97e121589ff27c753a16cb10830ae0f" 827 | 828 | [[package]] 829 | name = "vec_map" 830 | version = "0.8.2" 831 | source = "registry+https://github.com/rust-lang/crates.io-index" 832 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 833 | 834 | [[package]] 835 | name = "version_check" 836 | version = "0.9.4" 837 | source = "registry+https://github.com/rust-lang/crates.io-index" 838 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 839 | 840 | [[package]] 841 | name = "walkdir" 842 | version = "2.3.2" 843 | source = "registry+https://github.com/rust-lang/crates.io-index" 844 | checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" 845 | dependencies = [ 846 | "same-file", 847 | "winapi 0.3.9", 848 | "winapi-util", 849 | ] 850 | 851 | [[package]] 852 | name = "wasi" 853 | version = "0.10.0+wasi-snapshot-preview1" 854 | source = "registry+https://github.com/rust-lang/crates.io-index" 855 | checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" 856 | 857 | [[package]] 858 | name = "winapi" 859 | version = "0.2.8" 860 | source = "registry+https://github.com/rust-lang/crates.io-index" 861 | checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" 862 | 863 | [[package]] 864 | name = "winapi" 865 | version = "0.3.9" 866 | source = "registry+https://github.com/rust-lang/crates.io-index" 867 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 868 | dependencies = [ 869 | "winapi-i686-pc-windows-gnu", 870 | "winapi-x86_64-pc-windows-gnu", 871 | ] 872 | 873 | [[package]] 874 | name = "winapi-build" 875 | version = "0.1.1" 876 | source = "registry+https://github.com/rust-lang/crates.io-index" 877 | checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" 878 | 879 | [[package]] 880 | name = "winapi-i686-pc-windows-gnu" 881 | version = "0.4.0" 882 | source = "registry+https://github.com/rust-lang/crates.io-index" 883 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 884 | 885 | [[package]] 886 | name = "winapi-util" 887 | version = "0.1.5" 888 | source = "registry+https://github.com/rust-lang/crates.io-index" 889 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 890 | dependencies = [ 891 | "winapi 0.3.9", 892 | ] 893 | 894 | [[package]] 895 | name = "winapi-x86_64-pc-windows-gnu" 896 | version = "0.4.0" 897 | source = "registry+https://github.com/rust-lang/crates.io-index" 898 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 899 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------