monacoin-ruby 0.1.2 → 0.1.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,130 @@
1
+ # encoding: ascii-8bit
2
+ # port of https://github.com/trezor/python-mnemonic/blob/master/mnemonic/mnemonic.py
3
+
4
+ require 'openssl'
5
+ require 'securerandom'
6
+ require 'digest'
7
+
8
+ module Bitcoin
9
+ module Trezor
10
+
11
+ module Mnemonic
12
+ def self.to_seed(mnemonic, passphrase='')
13
+ OpenSSL::PKCS5.pbkdf2_hmac(mnemonic, 'mnemonic'+passphrase, 2048, 64, OpenSSL::Digest::SHA512.new).unpack("H*")[0]
14
+ end
15
+
16
+ def self.generate(strength_bits = 256)
17
+ raise ArgumentError, 'Strength should be divisible by 32, but it is not (%d)' % [strength_bits] if (strength_bits % 32) > 0
18
+ data = SecureRandom.random_bytes( (strength_bits / 8).floor )
19
+ to_mnemonic(data)
20
+ end
21
+
22
+ def self.wordlist
23
+ return @wordlist if @wordlist
24
+ @wordlist = WORDLIST_ENGLISH.split(/[ \n]/).map{|i| i.strip }
25
+ if @wordlist.size != (radix=2048)
26
+ raise ArgumentError, 'Wordlist should contain %d words, but it contains %d words.' % [radix, wordlist.size]
27
+ end
28
+ @wordlist
29
+ end
30
+
31
+ def self.to_mnemonic(data)
32
+ if (data.bytesize % 4) > 0
33
+ raise ArgumentError, 'Data length in bits should be divisible by 32, but it is not (%d bytes = %d bits).' % [data.bytesize, data.bytesize * 8]
34
+ end
35
+ b = data.unpack("B*")[0] + Digest::SHA256.digest(data).unpack("B*")[0].ljust(256, '0')[0...(data.bytesize * 8 / 32)]
36
+
37
+ (0...(b.bytesize / 11)).map{|i|
38
+ idx = b[ (i * 11)...((i+1) * 11) ].to_i(2)
39
+ wordlist[idx]
40
+ }.join(" ")
41
+ end
42
+
43
+ WORDLIST_ENGLISH = <<-TEXT
44
+ abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt
45
+ add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert
46
+ alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce
47
+ annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest
48
+ arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto
49
+ autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain
50
+ barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond
51
+ bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body
52
+ boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright
53
+ bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy
54
+ butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car
55
+ carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century
56
+ cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle
57
+ chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close
58
+ cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct
59
+ confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle
60
+ craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush
61
+ cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal
62
+ debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy
63
+ derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur
64
+ direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose
65
+ double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf
66
+ dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant
67
+ elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough
68
+ enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke
69
+ evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye
70
+ eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february
71
+ federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first
72
+ fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold
73
+ follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen
74
+ fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general
75
+ genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue
76
+ goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow
77
+ grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health
78
+ heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood
79
+ hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea
80
+ identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform
81
+ inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue
82
+ item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep
83
+ ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language
84
+ laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length
85
+ lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster
86
+ local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main
87
+ major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum
88
+ maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk
89
+ million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral
90
+ more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name
91
+ napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee
92
+ noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october
93
+ odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order
94
+ ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm
95
+ panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen
96
+ penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch
97
+ pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post
98
+ potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit
99
+ program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle
100
+ pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare
101
+ rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release
102
+ relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion
103
+ reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket
104
+ romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon
105
+ salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script
106
+ scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow
107
+ shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side
108
+ siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam
109
+ sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda
110
+ soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend
111
+ sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp
112
+ stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff
113
+ stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey
114
+ suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape
115
+ target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought
116
+ three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato
117
+ tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer
118
+ trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble
119
+ tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform
120
+ unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum
121
+ vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory
122
+ video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut
123
+ want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat
124
+ wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder
125
+ wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo
126
+ TEXT
127
+ end
128
+
129
+ end
130
+ end
@@ -0,0 +1,3 @@
1
+ module Bitcoin
2
+ VERSION = "0.1.3"
3
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: monacoin-ruby
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.2
4
+ version: 0.1.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - lian wrote original files, Tkobayashi added
@@ -32,6 +32,37 @@ files:
32
32
  - examples/connect.rb
33
33
  - examples/generate_tx.rb
34
34
  - examples/simple_network_monitor_and_util.rb
35
+ - lib/bitcoin.rb
36
+ - lib/bitcoin/bloom_filter.rb
37
+ - lib/bitcoin/builder.rb
38
+ - lib/bitcoin/connection.rb
39
+ - lib/bitcoin/contracthash.rb
40
+ - lib/bitcoin/dogecoin.rb
41
+ - lib/bitcoin/electrum/mnemonic.rb
42
+ - lib/bitcoin/ext_key.rb
43
+ - lib/bitcoin/ffi/bitcoinconsensus.rb
44
+ - lib/bitcoin/ffi/openssl.rb
45
+ - lib/bitcoin/ffi/secp256k1.rb
46
+ - lib/bitcoin/key.rb
47
+ - lib/bitcoin/litecoin.rb
48
+ - lib/bitcoin/logger.rb
49
+ - lib/bitcoin/protocol.rb
50
+ - lib/bitcoin/protocol/address.rb
51
+ - lib/bitcoin/protocol/alert.rb
52
+ - lib/bitcoin/protocol/aux_pow.rb
53
+ - lib/bitcoin/protocol/block.rb
54
+ - lib/bitcoin/protocol/handler.rb
55
+ - lib/bitcoin/protocol/parser.rb
56
+ - lib/bitcoin/protocol/partial_merkle_tree.rb
57
+ - lib/bitcoin/protocol/reject.rb
58
+ - lib/bitcoin/protocol/script_witness.rb
59
+ - lib/bitcoin/protocol/tx.rb
60
+ - lib/bitcoin/protocol/txin.rb
61
+ - lib/bitcoin/protocol/txout.rb
62
+ - lib/bitcoin/protocol/version.rb
63
+ - lib/bitcoin/script.rb
64
+ - lib/bitcoin/trezor/mnemonic.rb
65
+ - lib/bitcoin/version.rb
35
66
  - spec/bitcoin/bitcoin_spec.rb
36
67
  - spec/bitcoin/bloom_filter_spec.rb
37
68
  - spec/bitcoin/builder_spec.rb