libra_client 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +14 -0
  3. data/.travis.yml +7 -0
  4. data/CODE_OF_CONDUCT.md +74 -0
  5. data/Gemfile +4 -0
  6. data/Gemfile.lock +51 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +57 -0
  9. data/Rakefile +10 -0
  10. data/bin/console +16 -0
  11. data/bin/setup +8 -0
  12. data/gen_proto.sh +2 -0
  13. data/lib/libra/access_path.rb +51 -0
  14. data/lib/libra/account_address.rb +29 -0
  15. data/lib/libra/account_config.rb +57 -0
  16. data/lib/libra/account_resource.rb +38 -0
  17. data/lib/libra/mnemonic.rb +147 -0
  18. data/lib/libra/version.rb +3 -0
  19. data/lib/libra_client.rb +173 -0
  20. data/libra_client.gemspec +49 -0
  21. data/libra_client.sublime-project +16 -0
  22. data/proto-lib/access_path_pb.rb +17 -0
  23. data/proto-lib/account_state_blob_pb.rb +23 -0
  24. data/proto-lib/admission_control_pb.rb +37 -0
  25. data/proto-lib/admission_control_services_pb.rb +37 -0
  26. data/proto-lib/events_pb.rb +35 -0
  27. data/proto-lib/get_with_proof_pb.rb +88 -0
  28. data/proto-lib/ledger_info_pb.rb +31 -0
  29. data/proto-lib/mempool_status_pb.rb +21 -0
  30. data/proto-lib/proof_pb.rb +41 -0
  31. data/proto-lib/transaction_info_pb.rb +19 -0
  32. data/proto-lib/transaction_pb.rb +102 -0
  33. data/proto-lib/validator_change_pb.rb +19 -0
  34. data/proto-lib/vm_errors_pb.rb +215 -0
  35. data/protos/access_path.proto +11 -0
  36. data/protos/account_state_blob.proto +16 -0
  37. data/protos/admission_control.proto +76 -0
  38. data/protos/events.proto +38 -0
  39. data/protos/get_with_proof.proto +310 -0
  40. data/protos/ledger_info.proto +82 -0
  41. data/protos/mempool_status.proto +21 -0
  42. data/protos/proof.proto +72 -0
  43. data/protos/transaction.proto +170 -0
  44. data/protos/transaction_info.proto +26 -0
  45. data/protos/validator_change.proto +27 -0
  46. data/protos/vm_errors.proto +276 -0
  47. metadata +191 -0
@@ -0,0 +1,147 @@
1
+
2
+ require 'openssl'
3
+ require 'securerandom'
4
+ require 'digest'
5
+
6
+ module Libra
7
+
8
+ MNEMONIC_SALT_PREFIX = "LIBRA WALLET: mnemonic salt prefix$"
9
+ MASTER_KEY_SALT = "LIBRA WALLET: master key salt$"
10
+ INFO_PREFIX = "LIBRA WALLET: derived key$"
11
+
12
+ class Mnemonic
13
+ def self.to_seed(mnemonic, passphrase = 'LIBRA')
14
+ seed = OpenSSL::PKCS5.pbkdf2_hmac(
15
+ mnemonic, MNEMONIC_SALT_PREFIX + passphrase, 2048, 64, OpenSSL::Digest::SHA512.new
16
+ ) # how to support SHA3_256 in ruby?
17
+ seed.unpack('H*')[0].first
18
+ end
19
+
20
+ def self.generate(strength_bits = 256)
21
+ if (strength_bits % 32) > 0
22
+ raise ArgumentError, format(
23
+ 'Strength should be divisible by 32, but it is not (%<strength_bits>d)',
24
+ strength_bits: strength_bits
25
+ )
26
+ end
27
+ data = SecureRandom.random_bytes((strength_bits / 8).floor)
28
+ to_mnemonic(data)
29
+ end
30
+
31
+ def self.wordlist
32
+ @wordlist ||= nil
33
+ return @wordlist if @wordlist
34
+ @wordlist = WORDLIST_ENGLISH.split(/[ \n]/).map(&:strip).reject(&:empty?)
35
+ if @wordlist.size != (radix = 2048)
36
+ raise ArgumentError, format(
37
+ 'Wordlist should contain %<radix>d words, but it contains %<count>d words.',
38
+ radix: radix, count: wordlist.size
39
+ )
40
+ end
41
+ @wordlist
42
+ end
43
+
44
+ def self.to_mnemonic(data)
45
+ if (data.bytesize % 4) > 0
46
+ raise ArgumentError, format(
47
+ 'Data length in bits should be divisible by 32, ' \
48
+ 'but it is not (%<count>d bytes = %<bits_count>d bits).',
49
+ count: data.bytesize, bits_count: data.bytesize * 8
50
+ )
51
+ end
52
+ b = data.unpack('B*')[0] +
53
+ Digest::SHA256.digest(data).unpack('B*')[0]
54
+ .ljust(256, '0')[0...(data.bytesize * 8 / 32)]
55
+
56
+ (0...(b.bytesize / 11)).map do |i|
57
+ idx = b[(i * 11)...((i + 1) * 11)].to_i(2)
58
+ wordlist[idx]
59
+ end.join(' ')
60
+ end
61
+
62
+ WORDLIST_ENGLISH = <<-TEXT.freeze
63
+ 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
64
+ 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
65
+ 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
66
+ 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
67
+ 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
68
+ 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
69
+ 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
70
+ 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
71
+ 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
72
+ 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
73
+ 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
74
+ 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
75
+ 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
76
+ 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
77
+ 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
78
+ 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
79
+ 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
80
+ 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
81
+ 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
82
+ 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
83
+ 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
84
+ 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
85
+ 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
86
+ 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
87
+ 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
88
+ 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
89
+ 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
90
+ 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
91
+ 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
92
+ 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
93
+ 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
94
+ 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
95
+ 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
96
+ 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
97
+ 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
98
+ 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
99
+ 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
100
+ 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
101
+ 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
102
+ 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
103
+ 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
104
+ 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
105
+ 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
106
+ 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
107
+ 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
108
+ 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
109
+ 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
110
+ 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
111
+ 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
112
+ 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
113
+ 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
114
+ 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
115
+ 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
116
+ 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
117
+ 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
118
+ 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
119
+ 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
120
+ 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
121
+ 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
122
+ 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
123
+ 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
124
+ 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
125
+ 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
126
+ 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
127
+ 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
128
+ 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
129
+ 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
130
+ 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
131
+ 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
132
+ 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
133
+ 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
134
+ 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
135
+ 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
136
+ 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
137
+ 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
138
+ 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
139
+ 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
140
+ 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
141
+ 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
142
+ 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
143
+ 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
144
+ wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo
145
+ TEXT
146
+ end
147
+ end
@@ -0,0 +1,3 @@
1
+ module Libra
2
+ VERSION = "0.1.3"
3
+ end
@@ -0,0 +1,173 @@
1
+ protolib = File.expand_path(File.dirname(__FILE__) + '/../proto-lib')
2
+ $LOAD_PATH.unshift(protolib) if File.directory?(protolib) && !$LOAD_PATH.include?(protolib)
3
+
4
+ require 'grpc'
5
+ require 'admission_control_services_pb'
6
+ require 'canoser'
7
+ require 'rest_client'
8
+
9
+ require "libra/version"
10
+ require 'libra/account_address'
11
+ require 'libra/account_config'
12
+ require 'libra/access_path'
13
+ require 'libra/account_resource'
14
+ require 'libra/mnemonic'
15
+
16
+
17
+ module Libra
18
+ class LibraError < StandardError; end
19
+
20
+ module BinaryExtensions
21
+ # bin-to-hex
22
+ def bin2hex; unpack("H*")[0]; end
23
+ # hex-to-bin
24
+ def hex2bin; [self].pack("H*"); end
25
+ end
26
+
27
+ class ::String
28
+ include Libra::BinaryExtensions
29
+ end
30
+
31
+ NETWORKS = {
32
+ testnet:{
33
+ host: "ac.testnet.libra.org:8000",
34
+ faucet_host: "faucet.testnet.libra.org"
35
+ }
36
+ }
37
+
38
+
39
+ class Client
40
+
41
+ def initialize(network="testnet")
42
+ raise LibraError.new("only support testnet now.") unless network.to_s == "testnet"
43
+ @host = NETWORKS[network.to_sym][:host]
44
+ @faucet_host = NETWORKS[network.to_sym][:faucet_host]
45
+ end
46
+
47
+ def get_latest_transaction_version
48
+ stub = AdmissionControl::AdmissionControl::Stub.new(@host,:this_channel_is_insecure)
49
+ resp = stub.update_to_latest_ledger(Types::UpdateToLatestLedgerRequest.new())
50
+ resp.ledger_info_with_sigs.ledger_info.version
51
+ end
52
+
53
+ def update_to_latest_ledger(requested_items)
54
+ request = Types::UpdateToLatestLedgerRequest.new(client_known_version: 0, requested_items: requested_items)
55
+ stub = AdmissionControl::AdmissionControl::Stub.new(@host,:this_channel_is_insecure)
56
+ response = stub.update_to_latest_ledger(request)
57
+ # [:response_items, :ledger_info_with_sigs, :validator_change_events]
58
+ response
59
+ end
60
+
61
+ def get_sequence_number(address)
62
+ state = get_account_state(address)
63
+ state.sequence_number
64
+ end
65
+
66
+ def get_balance(address)
67
+ state = get_account_state(address)
68
+ state.balance
69
+ end
70
+
71
+ def get_account_state(address)
72
+ query = Types::GetAccountStateRequest.new(address: AccountAddress.hex_to_bytes(address))
73
+ item = Types::RequestItem.new(get_account_state_request: query)
74
+ resp = update_to_latest_ledger([item])
75
+ state = resp.response_items[0].get_account_state_response.account_state_with_proof
76
+ map = Libra::AccountState.deserialize(state.blob.blob).blob
77
+ resource = map[AccountConfig::ACCOUNT_RESOURCE_PATH]
78
+ Libra::AccountResource.deserialize(resource.pack('C*'))
79
+ end
80
+
81
+ def get_transactions(start_version, limit=1, fetch_events=false)
82
+ query = Types::GetTransactionsRequest.new(start_version: start_version, limit: limit, fetch_events: fetch_events)
83
+ item = Types::RequestItem.new(get_transactions_request: query)
84
+ resp = update_to_latest_ledger([item])
85
+ txn_list_with_proof = resp.response_items[0].get_transactions_response.txn_list_with_proof
86
+ #[:transactions, :infos, :events_for_versions, :first_transaction_version, :proof_of_first_transaction, :proof_of_last_transaction]
87
+ txn_list_with_proof.transactions
88
+ end
89
+
90
+ def get_transaction(start_version)
91
+ #Types::SignedTransaction [:raw_txn_bytes, :sender_public_key, :sender_signature]
92
+ get_transactions(start_version)[0]
93
+ end
94
+
95
+ def get_account_transaction(address, sequence_number, fetch_events=true)
96
+ addr = AccountAddress.hex_to_bytes(address)
97
+ query = Types::GetAccountTransactionBySequenceNumberRequest.new(account: addr, sequence_number: sequence_number, fetch_events: fetch_events)
98
+ item = Types::RequestItem.new(get_account_transaction_by_sequence_number_request: query)
99
+ resp = update_to_latest_ledger([item])
100
+ transaction = resp.response_items[0].get_account_transaction_by_sequence_number_response.signed_transaction_with_proof
101
+ #Types::SignedTransactionWithProof [:version, :signed_transaction, :proof, :events]
102
+ transaction
103
+ end
104
+
105
+ # Returns events specified by `access_path` with sequence number in range designated by
106
+ # `start_seq_num`, `ascending` and `limit`. If ascending is true this query will return up to
107
+ # `limit` events that were emitted after `start_event_seq_num`. Otherwise it will return up to
108
+ # `limit` events in the reverse order. Both cases are inclusive.
109
+ def get_events(address_hex, path, start_sequence_number, ascending=true, limit=1)
110
+ access_path = AccessPath.new(address_hex, path).to_proto
111
+ query = Types::GetEventsByEventAccessPathRequest.new(access_path: access_path, start_event_seq_num: start_sequence_number, ascending: ascending, limit: limit)
112
+ item = Types::RequestItem.new(get_events_by_event_access_path_request: query)
113
+ resp = update_to_latest_ledger([item])
114
+ resp.response_items[0].get_events_by_event_access_path_response.events_with_proof
115
+ end
116
+
117
+ def get_events_sent(address_hex, start_sequence_number, ascending=true, limit=1)
118
+ path = AccountConfig.account_sent_event_path
119
+ get_events(address_hex, path, start_sequence_number, ascending, limit)
120
+ end
121
+
122
+ def get_events_received(address_hex, start_sequence_number, ascending=true, limit=1)
123
+ path = AccountConfig.account_received_event_path
124
+ get_events(address_hex, path, start_sequence_number, ascending, limit)
125
+ end
126
+
127
+ def get_latest_events_sent(address_hex, limit=1)
128
+ get_events_sent(address_hex, 2**64-1, false, limit)
129
+ end
130
+
131
+ def get_latest_events_received(address_hex, limit=1)
132
+ get_events_received(address_hex, 2**64-1, false, limit)
133
+ end
134
+
135
+ def mint_coins_with_local_faucet_account
136
+ end
137
+
138
+ def mint_coins_with_faucet_service(receiver, num_coins, is_blocking)
139
+ resp = RestClient.post "http://#{@faucet_host}?amount=#{num_coins}&address=#{receiver}", {}
140
+ if resp.code != 200
141
+ raise LibraError.new("Failed to query remote faucet server[status=#{resp.code}]: #{resp.body}")
142
+ end
143
+ sequence_number = resp.body.to_i
144
+ if is_blocking
145
+ puts AccountConfig.association_address.hex
146
+ self.wait_for_transaction(AccountConfig.association_address.hex, sequence_number);
147
+ end
148
+ end
149
+
150
+ def wait_for_transaction(account, sequence_number)
151
+ max_iterations = 500
152
+ puts("waiting ")
153
+ while (max_iterations > 0 )do
154
+ $stdout.flush
155
+ max_iterations -= 1;
156
+ transaction = get_account_transaction(account, sequence_number - 1, true)
157
+ if transaction && transaction.events
158
+ puts "transaction is stored!"
159
+ if transaction.events.events.size == 0
160
+ puts "no events emitted"
161
+ end
162
+ return
163
+ else
164
+ print(".")
165
+ sleep(0.01)
166
+ end
167
+ end
168
+ puts "wait_for_transaction timeout"
169
+ end
170
+
171
+ end
172
+
173
+ end
@@ -0,0 +1,49 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "libra/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "libra_client"
8
+ spec.version = Libra::VERSION
9
+ spec.authors = ["yuan xinyu"]
10
+ spec.email = ["yuanxinyu.hangzhou@gmail.com"]
11
+
12
+ spec.summary = %q{A ruby client for Libra network.}
13
+ spec.description = %q{A ruby client for Libra network.}
14
+ spec.homepage = "https://github.com/yuanxinyu/libra_client.git"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
21
+
22
+ spec.metadata["homepage_uri"] = spec.homepage
23
+ spec.metadata["source_code_uri"] = "https://github.com/yuanxinyu/libra_client.git"
24
+ spec.metadata["changelog_uri"] = "https://github.com/yuanxinyu/libra_client.git"
25
+ else
26
+ raise "RubyGems 2.0 or newer is required to protect against " \
27
+ "public gem pushes."
28
+ end
29
+
30
+ # Specify which files should be added to the gem when it is released.
31
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
32
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
33
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
34
+ end
35
+ spec.bindir = "exe"
36
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
37
+ spec.require_paths = ["lib"]
38
+
39
+ spec.add_development_dependency "bundler", "~> 2.0"
40
+ spec.add_development_dependency "rake", "~> 10.0"
41
+ spec.add_development_dependency "minitest", "~> 5.0"
42
+ spec.add_development_dependency "byebug", "~> 11.0"
43
+
44
+ spec.add_dependency "grpc", "~> 1.23"
45
+ spec.add_dependency "canoser", "~> 0.1.2"
46
+ spec.add_dependency "rest-client", "~> 2.0"
47
+ #spec.add_dependency "openssl", "~> 3.0.0" #not ready, need SHA3 support.
48
+
49
+ end
@@ -0,0 +1,16 @@
1
+ {
2
+ "folders":
3
+ [
4
+ {
5
+ "path": ".",
6
+ "folder_exclude_patterns": [".bundle",".idea","certs","coverage","tmp","log","pkg"],
7
+ "file_exclude_patterns": ["*.sublime-workspace","*.sqlite3","spec/examples.txt",".byebug_history",".DS_Store"]
8
+ }
9
+ ],
10
+ "settings":
11
+ {
12
+ "translate_tabs_to_spaces": true,
13
+ "trim_trailing_white_space_on_save": true,
14
+ "tab_size": 2
15
+ }
16
+ }
@@ -0,0 +1,17 @@
1
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ # source: access_path.proto
3
+
4
+ require 'google/protobuf'
5
+
6
+ Google::Protobuf::DescriptorPool.generated_pool.build do
7
+ add_file("access_path.proto", :syntax => :proto3) do
8
+ add_message "types.AccessPath" do
9
+ optional :address, :bytes, 1
10
+ optional :path, :bytes, 2
11
+ end
12
+ end
13
+ end
14
+
15
+ module Types
16
+ AccessPath = Google::Protobuf::DescriptorPool.generated_pool.lookup("types.AccessPath").msgclass
17
+ end
@@ -0,0 +1,23 @@
1
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ # source: account_state_blob.proto
3
+
4
+ require 'google/protobuf'
5
+
6
+ require 'proof_pb'
7
+ Google::Protobuf::DescriptorPool.generated_pool.build do
8
+ add_file("account_state_blob.proto", :syntax => :proto3) do
9
+ add_message "types.AccountStateBlob" do
10
+ optional :blob, :bytes, 1
11
+ end
12
+ add_message "types.AccountStateWithProof" do
13
+ optional :version, :uint64, 1
14
+ optional :blob, :message, 2, "types.AccountStateBlob"
15
+ optional :proof, :message, 3, "types.AccountStateProof"
16
+ end
17
+ end
18
+ end
19
+
20
+ module Types
21
+ AccountStateBlob = Google::Protobuf::DescriptorPool.generated_pool.lookup("types.AccountStateBlob").msgclass
22
+ AccountStateWithProof = Google::Protobuf::DescriptorPool.generated_pool.lookup("types.AccountStateWithProof").msgclass
23
+ end
@@ -0,0 +1,37 @@
1
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ # source: admission_control.proto
3
+
4
+ require 'google/protobuf'
5
+
6
+ require 'get_with_proof_pb'
7
+ require 'transaction_pb'
8
+ require 'proof_pb'
9
+ require 'ledger_info_pb'
10
+ require 'vm_errors_pb'
11
+ require 'mempool_status_pb'
12
+ Google::Protobuf::DescriptorPool.generated_pool.build do
13
+ add_file("admission_control.proto", :syntax => :proto3) do
14
+ add_message "admission_control.SubmitTransactionRequest" do
15
+ optional :signed_txn, :message, 1, "types.SignedTransaction"
16
+ end
17
+ add_message "admission_control.SubmitTransactionResponse" do
18
+ optional :validator_id, :bytes, 4
19
+ oneof :status do
20
+ optional :vm_status, :message, 1, "types.VMStatus"
21
+ optional :ac_status, :enum, 2, "admission_control.AdmissionControlStatus"
22
+ optional :mempool_status, :enum, 3, "mempool.MempoolAddTransactionStatus"
23
+ end
24
+ end
25
+ add_enum "admission_control.AdmissionControlStatus" do
26
+ value :Accepted, 0
27
+ value :Blacklisted, 1
28
+ value :Rejected, 2
29
+ end
30
+ end
31
+ end
32
+
33
+ module AdmissionControl
34
+ SubmitTransactionRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("admission_control.SubmitTransactionRequest").msgclass
35
+ SubmitTransactionResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup("admission_control.SubmitTransactionResponse").msgclass
36
+ AdmissionControlStatus = Google::Protobuf::DescriptorPool.generated_pool.lookup("admission_control.AdmissionControlStatus").enummodule
37
+ end