peatio-ripple 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 8c1de3483d3a5f2c7b685c4cc612f8e39d201988d3d81e8da012d44bbc8f9523
4
+ data.tar.gz: 02c6b760456d93918934131b4fd4a53f4bb88e3279467374f14ecf4933015324
5
+ SHA512:
6
+ metadata.gz: 76f12afea9bf30002d4dff575aa6a7d9ca00deb359e958a5e2dc6c9048b684be6291e1209c9f0bea38476339303acfe5059df431d8bb5bb1a2bc8bacaa29cba7
7
+ data.tar.gz: ed9a292cc19708c92f7f1abfde35c4558fb4a90a7ae15d6d3fab93f87a137e1dc5fc4637c67556ff87ca1ee1cbbe307abcc95a41e3ef8b87df583ea511547b3f
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.0
7
+ before_install: gem install bundler -v 1.17.2
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in peatio-ripple.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,110 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ peatio-ripple (0.1.0)
5
+ activesupport (~> 5.2.3)
6
+ better-faraday (~> 1.0.5)
7
+ faraday (~> 0.15.4)
8
+ memoist (~> 0.16.0)
9
+ peatio (~> 0.6.1)
10
+
11
+ GEM
12
+ remote: https://rubygems.org/
13
+ specs:
14
+ activemodel (5.2.3)
15
+ activesupport (= 5.2.3)
16
+ activesupport (5.2.3)
17
+ concurrent-ruby (~> 1.0, >= 1.0.2)
18
+ i18n (>= 0.7, < 2)
19
+ minitest (~> 5.1)
20
+ tzinfo (~> 1.1)
21
+ addressable (2.6.0)
22
+ public_suffix (>= 2.0.2, < 4.0)
23
+ amq-protocol (2.3.0)
24
+ amqp (1.8.0)
25
+ amq-protocol (>= 2.2.0)
26
+ eventmachine
27
+ better-faraday (1.0.6)
28
+ activesupport (>= 4.0, < 6.0)
29
+ faraday (~> 0.12)
30
+ bunny (2.14.2)
31
+ amq-protocol (~> 2.3, >= 2.3.0)
32
+ byebug (11.0.1)
33
+ clamp (1.3.1)
34
+ coderay (1.1.2)
35
+ concurrent-ruby (1.1.5)
36
+ crack (0.4.3)
37
+ safe_yaml (~> 1.0.0)
38
+ diff-lcs (1.3)
39
+ em-websocket (0.5.1)
40
+ eventmachine (>= 0.12.9)
41
+ http_parser.rb (~> 0.6.0)
42
+ eventmachine (1.2.7)
43
+ faraday (0.15.4)
44
+ multipart-post (>= 1.2, < 3)
45
+ hashdiff (0.3.9)
46
+ http_parser.rb (0.6.0)
47
+ i18n (1.6.0)
48
+ concurrent-ruby (~> 1.0)
49
+ jwt (2.2.1)
50
+ memoist (0.16.0)
51
+ metaclass (0.0.4)
52
+ method_source (0.9.2)
53
+ minitest (5.11.3)
54
+ mocha (1.8.0)
55
+ metaclass (~> 0.0.1)
56
+ multipart-post (2.1.1)
57
+ mysql2 (0.5.2)
58
+ peatio (0.6.1)
59
+ activemodel (~> 5.2.3)
60
+ amqp
61
+ bunny
62
+ clamp
63
+ em-websocket
64
+ eventmachine
65
+ jwt
66
+ mysql2
67
+ pry (0.12.2)
68
+ coderay (~> 1.1.0)
69
+ method_source (~> 0.9.0)
70
+ pry-byebug (3.7.0)
71
+ byebug (~> 11.0)
72
+ pry (~> 0.10)
73
+ public_suffix (3.0.3)
74
+ rake (10.5.0)
75
+ rspec (3.8.0)
76
+ rspec-core (~> 3.8.0)
77
+ rspec-expectations (~> 3.8.0)
78
+ rspec-mocks (~> 3.8.0)
79
+ rspec-core (3.8.0)
80
+ rspec-support (~> 3.8.0)
81
+ rspec-expectations (3.8.2)
82
+ diff-lcs (>= 1.2.0, < 2.0)
83
+ rspec-support (~> 3.8.0)
84
+ rspec-mocks (3.8.0)
85
+ diff-lcs (>= 1.2.0, < 2.0)
86
+ rspec-support (~> 3.8.0)
87
+ rspec-support (3.8.0)
88
+ safe_yaml (1.0.5)
89
+ thread_safe (0.3.6)
90
+ tzinfo (1.2.5)
91
+ thread_safe (~> 0.1)
92
+ webmock (3.5.1)
93
+ addressable (>= 2.3.6)
94
+ crack (>= 0.3.2)
95
+ hashdiff
96
+
97
+ PLATFORMS
98
+ ruby
99
+
100
+ DEPENDENCIES
101
+ bundler (~> 1.17)
102
+ mocha (~> 1.8)
103
+ peatio-ripple!
104
+ pry-byebug
105
+ rake (~> 10.0)
106
+ rspec (~> 3.0)
107
+ webmock (~> 3.5)
108
+
109
+ BUNDLED WITH
110
+ 1.17.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Maksym Naichuk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # Peatio::Ripple
2
+
3
+ Peatio ripple plugin for Rubykube stack
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'peatio-ripple'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install peatio-ripple
20
+
21
+ ## Usage
22
+
23
+ For Peatio Ripple plugin integration you need to do the following steps:
24
+
25
+ ### Image Build.
26
+
27
+ 1. Add peatio-ripple gem into your Gemfile.plugin
28
+ ```ruby
29
+ gem 'peatio-ripple', '~> 0.2.0'
30
+ ```
31
+
32
+ 2. Run `bundle install` for updating Gemfile.lock
33
+
34
+ 3. Build custom Peatio [docker image with Ripple plugin](https://github.com/rubykube/peatio/blob/master/docs/plugins.md#build)
35
+
36
+ 4. Push your image using `docker push`
37
+
38
+ 5. Update your deployment to use image with peatio-ripple gem
39
+
40
+ ### Peatio Configuration.
41
+
42
+ 1. Create Ripple Blockchain [config example](../config/blockchains.yml).
43
+ * No additional steps are needed
44
+
45
+ 2. Create Ripple Currency [config example](../config/currencies.yml).
46
+ * No additional steps are needed
47
+
48
+ 3. Create Ripple Wallets [config example](../config/wallets.yml)(deposit and hot wallets are required).
49
+ * No additional steps are needed
50
+
51
+
52
+ ## Development
53
+
54
+ Plugin development [example](https://github.com/rubykube/peatio/blob/master/docs/coins/development.md).
55
+
56
+ ## Contributing
57
+
58
+ Bug reports and pull requests are welcome on GitHub at https://github.com/rubykube/peatio-ripple.
59
+
60
+ ## License
61
+
62
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
63
+
64
+ ## Consulting
65
+
66
+ You can contact Openware for finding certified vendors:
67
+ [Openware.com](https://www.openware.com)
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "peatio/ripple"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,10 @@
1
+ - key: xrp-testnet
2
+ name: Ripple Testnet
3
+ client: ripple # API client name.
4
+ server: http://user:password@127.0.0.1:5005 # Public Ripple node endpoint.
5
+ height: 19706874 # Initial block number from which sync will be started.
6
+ min_confirmations: 6 # Minimal confirmations needed for withdraw and deposit confirmation.
7
+ explorer:
8
+ address: https://test.bithomp.com/explorer/#{address}
9
+ transaction: https://test.bithomp.com/explorer/#{txid}
10
+ status: active
@@ -0,0 +1,18 @@
1
+ - id: xrp
2
+ name: Ripple
3
+ blockchain_key: xrp-testnet
4
+ symbol: 'ꭆ'
5
+ type: coin
6
+ precision: 8
7
+ base_factor: 1_000_000
8
+ enabled: true
9
+ # Deposits with less amount are skipped during blockchain synchronization.
10
+ # We advise to set value 10 times bigger than the network fee to prevent losses.
11
+ min_deposit_amount: 0.0001
12
+ min_collection_amount: 0.0001
13
+ withdraw_limit_24h: 100
14
+ withdraw_limit_72h: 200
15
+ deposit_fee: 0
16
+ withdraw_fee: 0
17
+ position: 1
18
+ options: {}
@@ -0,0 +1,46 @@
1
+ - name: Ripple Deposit Wallet
2
+ blockchain_key: xrp-testnet
3
+ currency_id: xrp
4
+ address: 'r4kpJtnx4goLYXoRdi7mbkRpZ9Xpx2RyPN' # IMPORTANT: Always wrap this value in quotes!
5
+ kind: deposit # Wallet kind (deposit, hot, warm, cold or fee).
6
+ nsig: 1 # Number of signatures required for performing withdraw.
7
+ max_balance: 0.0
8
+ status: active
9
+ gateway: rippled # Gateway client name.
10
+ settings:
11
+ #
12
+ # Rippled gateway client settings.
13
+ uri: http://127.0.0.1:5005
14
+ secret: 'changeme'
15
+
16
+ - name: Ripple Hot Wallet
17
+ blockchain_key: xrp-testnet
18
+ currency_id: xrp
19
+ # Address where deposits will be collected to.
20
+ address: 'r4kpJtnx4goLYXoRdi7mbkRpZ9Xpx2RyPN' # IMPORTANT: Always wrap this value in quotes!
21
+ kind: hot # Wallet kind (deposit, hot, warm, cold or fee).
22
+ nsig: 1 # Number of signatures required for performing withdraw.
23
+ max_balance: 100.0
24
+ status: active
25
+ gateway: rippled # Gateway client name.
26
+ settings:
27
+ #
28
+ # Rippled gateway client settings.
29
+ uri: http://127.0.0.1:5005
30
+ secret: 'changeme'
31
+
32
+ - name: Ripple Warm Wallet
33
+ blockchain_key: xrp-testnet
34
+ currency_id: xrp
35
+ # Address where deposits will be collected to.
36
+ address: 'r4kpJtnx4goLYXoRdi7mbkRpZ9Xpx2RyPN' # IMPORTANT: Always wrap this value in quotes!
37
+ kind: warm # Wallet kind (deposit, hot, warm, cold or fee).
38
+ nsig: 1 # Number of signatures required for performing withdraw.
39
+ max_balance: 1000.0
40
+ status: active
41
+ gateway: rippled # Gateway client name.
42
+ settings:
43
+ #
44
+ # Rippled gateway client settings.
45
+ uri: http://user:password@127.0.0.1:5005
46
+ secret: 'changeme'
@@ -0,0 +1,29 @@
1
+ # Integration.
2
+
3
+ For Peatio Ripple plugin integration you need to do the following steps:
4
+
5
+ ## Image Build.
6
+
7
+ 1. Add peatio-ripple gem into your Gemfile.plugin
8
+ ```ruby
9
+ gem 'peatio-ripple', '~> 0.1.0'
10
+ ```
11
+
12
+ 2. Run `bundle install` for updating Gemfile.lock
13
+
14
+ 3. Build custom Peatio [docker image with Ripple plugin](https://github.com/rubykube/peatio/blob/master/docs/plugins.md#build)
15
+
16
+ 4. Push your image using `docker push`
17
+
18
+ 5. Update your deployment to use image with peatio-ripple gem
19
+
20
+ ## Peatio Configuration.
21
+
22
+ 1. Create Ripple Blockchain [config example](../config/blockchains.yml).
23
+ * No additional steps are needed
24
+
25
+ 2. Create Ripple Currency [config example](../config/currencies.yml).
26
+ * No additional steps are needed
27
+
28
+ 3. Create Ripple Wallets [config example](../config/wallets.yml)(deposit and hot wallets are required).
29
+ * No additional steps are needed
data/docs/json-rpc.md ADDED
@@ -0,0 +1,31 @@
1
+ # JSON RPC
2
+
3
+ The next list of JSON RPC calls where used for plugin development.
4
+ For response examples see spec/resources:
5
+
6
+ * account_info
7
+ `curl --data-binary '{"jsonrpc":"2.0","id":1,"method":"fee", "params": [{}]}' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
8
+
9
+ * fee
10
+ `curl --data-binary '{"jsonrpc":"2.0","id":1,"method":"ledger", "params": [{ "ledger_index": "validated" }]}' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
11
+
12
+ * ledger
13
+ `curl --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockcount", "params": [] }' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
14
+
15
+ * ledger(transaction: true)
16
+ `curl --data-binary '{"jsonrpc":"2.0","id":1,"method":"ledger", "params": [{ "ledger_index": "validated", "transactions": true }]}' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
17
+
18
+ * sign
19
+ `curl --data-binary '{"jsonrpc":"2.0","id":1,"method":"sign", "params": [{ "secret": "snKAbE6d1wPqeaDai541Wirqq3Pd3", "tx_json": { "Account": "rsFyWHyiDd2bvbnAFPXZnsZyfcQttv4T4c", "Amount": "10000000", "Fee":"10", "Destination": "rB94e2mZZcApwEFeW6oWuME351w1yQpJQy", "TransactionType": "Payment", "LastLedgerSequence": 19697030 } }]}' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
20
+
21
+ * submit
22
+ `curl --data-binary '{"jsonrpc":"2.0","id":1,"method":"submit", "params": [{ "tx_blob": "12000022800000002400000001201B012C8FC061400000000098968068400000000000000A732102B9C6E7141E6C573B4B458EDA44A1E823C404AA16142C1F26EF714163A3F2FB6E7446304402206796D95E0DF6F0012AE1679B37A2254677E3492CE41261FC23E2BBDBDAF8B93302202C70611478BA8AAB1C7A97C472C9CC9C4A315349CD90C2DDDDD84C95AD938E8381141F02F845784D34EF689AE436709184E69BF17A8883146F46A80656A321D5A1E2224A73DA60C23F218A93" }]}' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
23
+
24
+ * tx
25
+ `curl --data-binary '{"jsonrpc":"2.0","id":1,"method":"tx", "params": [{ "transaction": "70C40F4A172051B786E954ADE38080311BEE81C788B4257C67F1DBCB7D487F24" }]}' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
26
+
27
+ * wallet_propose
28
+ `curl --data-binary '{"jsonrpc":"2.0","id":1,"method":"wallet_propose", "params": [{ "key_type": "secp256k1"}]}' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
29
+
30
+ * methodnotfound
31
+ `curl --data-binary '{"jsonrpc": "2.0", "id": 1, "method": "methodnotfound", "params": [] }' -H 'Content-Type: application/json' http://user:password@127.0.0.1:5005`
data/docs/testnet.md ADDED
@@ -0,0 +1,13 @@
1
+ # Getting Ripple in testnet.
2
+
3
+ ## Faucet
4
+
5
+ * [developers.ripple.com](https://developers.ripple.com/xrp-test-net-faucet.html)
6
+
7
+ ## Wallet
8
+
9
+ * [ripplerm.github.io](https://ripplerm.github.io/ripple-wallet/)
10
+
11
+ ## Explorer
12
+
13
+ * [test.bithomp.com](https://test.bithomp.com/explorer/)
@@ -0,0 +1,15 @@
1
+ require "peatio/ripple/version"
2
+ require "active_support/core_ext/object/blank"
3
+ require "peatio"
4
+
5
+ module Peatio
6
+ module Ripple
7
+ require "peatio/ripple/client"
8
+ require "peatio/ripple/blockchain"
9
+ require "peatio/ripple/wallet"
10
+ require "peatio/ripple/password_generator"
11
+
12
+ require "peatio/ripple/hooks"
13
+ require "peatio/ripple/version"
14
+ end
15
+ end
@@ -0,0 +1,133 @@
1
+
2
+ module Peatio
3
+ module Ripple
4
+ class Blockchain < Peatio::Blockchain::Abstract
5
+
6
+ # Flow:
7
+ # get block_number from params
8
+ # fetch transactions from this block
9
+ # build transactions from prev step
10
+
11
+ UndefinedCurrencyError = Class.new(StandardError)
12
+
13
+ DEFAULT_FEATURES = { case_sensitive: true, cash_addr_format: false }.freeze
14
+
15
+ def initialize(custom_features = {})
16
+ @features = DEFAULT_FEATURES.merge(custom_features).slice(*SUPPORTED_FEATURES)
17
+ @settings = {}
18
+ end
19
+
20
+ def configure(settings = {})
21
+ # Clean client state during configure.
22
+ @client = nil
23
+ @settings.merge!(settings.slice(*SUPPORTED_SETTINGS))
24
+ end
25
+
26
+ def fetch_block!(ledger_index)
27
+ ledger = client.json_rpc(:ledger,
28
+ [
29
+ {
30
+ ledger_index: ledger_index || 'validated',
31
+ transactions: true,
32
+ expand: true
33
+ }
34
+ ]).dig('ledger')
35
+
36
+ return if ledger.blank?
37
+ ledger.fetch('transactions').each_with_object([]) do |tx, txs_array|
38
+ next unless valid_transaction?(tx)
39
+
40
+ txs = build_transaction(tx).map do |ntx|
41
+ Peatio::Transaction.new(ntx.merge(block_number: ledger_index))
42
+ end
43
+ txs_array.append(*txs)
44
+ end.yield_self { |txs_array| Peatio::Block.new(ledger_index, txs_array) }
45
+ rescue Client::Error => e
46
+ raise Peatio::Blockchain::ClientError, e
47
+ end
48
+
49
+ def latest_block_number
50
+ client.json_rpc(:ledger, [{ ledger_index: 'validated' }]).fetch('ledger_index')
51
+ rescue Client::Error => e
52
+ raise Peatio::Blockchain::ClientError, e
53
+ end
54
+
55
+ def load_balance_of_address!(address, currency_id)
56
+ currency = settings[:currencies].find { |c| c[:id] == currency_id.to_s }
57
+ raise UndefinedCurrencyError unless currency
58
+
59
+ client.json_rpc(:account_info,
60
+ [account: normalize_address(address), ledger_index: 'validated', strict: true])
61
+ .fetch('account_data')
62
+ .fetch('Balance')
63
+ .to_d
64
+ .yield_self { |amount| convert_from_base_unit(amount, currency) }
65
+
66
+ rescue Client::Error => e
67
+ raise Peatio::Blockchain::ClientError, e
68
+ end
69
+
70
+ private
71
+
72
+ def build_transaction(tx_hash)
73
+ destination_tag = tx_hash['DestinationTag'] || destination_tag_from(tx_hash['Destination'])
74
+ address = "#{to_address(tx_hash)}?dt=#{destination_tag}"
75
+
76
+ settings_fetch(:currencies).each_with_object([]) do |currency, formatted_txs|
77
+ formatted_txs << { hash: tx_hash['hash'],
78
+ txout: tx_hash.dig('metaData','TransactionIndex'),
79
+ to_address: address,
80
+ status: check_status(tx_hash),
81
+ currency_id: currency[:id],
82
+ amount: convert_from_base_unit(tx_hash.fetch('Amount'), currency) }
83
+ end
84
+ end
85
+
86
+ def settings_fetch(key)
87
+ @settings.fetch(key) { raise Peatio::Blockchain::MissingSettingError, key.to_s }
88
+ end
89
+
90
+ def check_status(tx_hash)
91
+ tx_hash.dig('metaData', 'TransactionResult') == 'tesSUCCESS' ? 'success' : 'failed'
92
+ end
93
+
94
+ def valid_transaction?(tx)
95
+ inspect_address!(tx['Account'])[:is_valid] &&
96
+ tx['TransactionType'].to_s == 'Payment' &&
97
+ String === tx['Amount']
98
+ end
99
+
100
+ def inspect_address!(address)
101
+ {
102
+ address: normalize_address(address),
103
+ is_valid: valid_address?(normalize_address(address))
104
+ }
105
+ end
106
+
107
+ def normalize_address(address)
108
+ address.gsub(/\?dt=\d*\Z/, '')
109
+ end
110
+
111
+ def valid_address?(address)
112
+ /\Ar[0-9a-zA-Z]{33}(:?\?dt=[1-9]\d*)?\z/.match?(address)
113
+ end
114
+
115
+ def destination_tag_from(address)
116
+ address =~ /\?dt=(\d*)\Z/
117
+ $1.to_i
118
+ end
119
+
120
+ def to_address(tx)
121
+ normalize_address(tx['Destination'])
122
+ end
123
+
124
+ def convert_from_base_unit(value, currency)
125
+ value.to_d / currency.fetch(:base_factor).to_d
126
+ end
127
+
128
+ def client
129
+ @client ||= Client.new(settings_fetch(:server))
130
+ end
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,68 @@
1
+ require 'memoist'
2
+ require 'faraday'
3
+ require 'better-faraday'
4
+
5
+ module Peatio
6
+ module Ripple
7
+ class Client
8
+ Error = Class.new(StandardError)
9
+ class ConnectionError < Error; end
10
+
11
+ class ResponseError < Error
12
+ def initialize(code, msg)
13
+ @code = code
14
+ @msg = msg
15
+ end
16
+
17
+ def message
18
+ "#{@msg} (#{@code})"
19
+ end
20
+ end
21
+
22
+ extend Memoist
23
+
24
+ def initialize(endpoint)
25
+ @json_rpc_endpoint = URI.parse(endpoint)
26
+ @json_rpc_call_id = 0
27
+ end
28
+
29
+ def json_rpc(method, params = [])
30
+ response = connection.post \
31
+ '/',
32
+ { jsonrpc: '2.0', id: rpc_call_id, method: method, params: params }.to_json,
33
+ { 'Accept' => 'application/json',
34
+ 'Content-Type' => 'application/json' }
35
+ response.assert_2xx!
36
+ response = JSON.parse(response.body)
37
+ response.fetch('result').tap do |result|
38
+ raise ResponseError.new(result['error_code'], result['error_message']) if result['status'] == 'error'
39
+ end
40
+ response.fetch('result')
41
+ rescue => e
42
+ if e.is_a?(Error)
43
+ raise e, e.message
44
+ elsif e.is_a?(Faraday::Error)
45
+ raise ConnectionError, e
46
+ else
47
+ raise Error, e
48
+ end
49
+ end
50
+
51
+ private
52
+
53
+ def rpc_call_id
54
+ @json_rpc_call_id += 1
55
+ end
56
+
57
+ def connection
58
+ Faraday.new(@json_rpc_endpoint).tap do |connection|
59
+ unless @json_rpc_endpoint.user.blank?
60
+ connection.basic_auth(@json_rpc_endpoint.user,
61
+ @json_rpc_endpoint.password)
62
+ end
63
+ end
64
+ end
65
+ memoize :connection
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,35 @@
1
+ module Peatio
2
+ module Ripple
3
+ module Hooks
4
+ class << self
5
+ def check_compatibility
6
+ if Peatio::Blockchain::VERSION >= '2.0'
7
+ [
8
+ "Ripple plugin was designed for work with 1.x. Blockchain.",
9
+ "You have #{Peatio::Ripple::Blockchain::VERSION}."
10
+ ].join('\n').tap { |s| Kernel.abort s }
11
+ end
12
+
13
+ if Peatio::Wallet::VERSION >= '2.0'
14
+ [
15
+ "Ripple plugin was designed for work with 1.x. Wallet.",
16
+ "You have #{Peatio::Ripple::Wallet::VERSION}."
17
+ ].join('\n').tap { |s| Kernel.abort s }
18
+ end
19
+ end
20
+
21
+ def register
22
+ Peatio::Blockchain.registry[:ripple] = Ripple::Blockchain.new
23
+ Peatio::Wallet.registry[:rippled] = Ripple::Wallet.new
24
+ end
25
+ end
26
+
27
+ if defined?(Rails::Railtie)
28
+ require "peatio/ripple/railtie"
29
+ else
30
+ check_compatibility
31
+ register
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,21 @@
1
+ # encoding: UTF-8
2
+ # frozen_string_literal: true
3
+
4
+ #= PasswordGenerator
5
+ #
6
+ #== Usage
7
+ #
8
+ # >> PasswordGenerator.generate
9
+ # => "2pN@cxj+zs!SVogtPZ&u"
10
+ #
11
+ # >> PasswordGenerator.generate(40)
12
+ # => "B5xPy2unMKjRchfS($7v)q4N%oF*lGz@+OJ6LbVD"
13
+ module PasswordGenerator
14
+ CHARS = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a + %w{! @ # $ % & / ( ) + ? *}
15
+
16
+ class << self
17
+ def generate(length = 20)
18
+ CHARS.sort_by { rand }.join[0...length]
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,13 @@
1
+ module Peatio
2
+ module Ripple
3
+ class Railtie < Rails::Railtie
4
+ config.before_initialize do
5
+ Hooks.check_compatibility
6
+ end
7
+
8
+ config.after_initialize do
9
+ Hooks.register
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,5 @@
1
+ module Peatio
2
+ module Ripple
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,152 @@
1
+ module Peatio
2
+ module Ripple
3
+ class Wallet < Peatio::Wallet::Abstract
4
+
5
+ Error = Class.new(StandardError)
6
+
7
+ def initialize(settings = {})
8
+ @settings = settings
9
+ end
10
+
11
+ def configure(settings = {})
12
+ # Clean client state during configure.
13
+ @client = nil
14
+ @settings.merge!(settings.slice(*SUPPORTED_SETTINGS))
15
+
16
+ @wallet = @settings.fetch(:wallet) do
17
+ raise Peatio::Wallet::MissingSettingError, :wallet
18
+ end.slice(:uri, :address, :secret)
19
+
20
+ @currency = @settings.fetch(:currency) do
21
+ raise Peatio::Wallet::MissingSettingError, :currency
22
+ end.slice(:id, :base_factor, :options)
23
+ end
24
+
25
+ def create_address!(_setting)
26
+ {
27
+ address: "#{@wallet[:address]}?dt=#{SecureRandom.random_number(10**9)}",
28
+ secret: @wallet[:secret]
29
+ }
30
+ end
31
+
32
+ def create_raw_address(options = {})
33
+ secret = options.fetch(:secret) { PasswordGenerator.generate(64) }
34
+ result = client.json_rpc(:wallet_propose, [{ passphrase: secret }])
35
+
36
+ result.slice('key_type', 'master_seed', 'master_seed_hex',
37
+ 'master_key', 'public_key', 'public_key_hex')
38
+ .merge(address: normalize_address(result.fetch('account_id')), secret: secret)
39
+ .symbolize_keys
40
+ end
41
+
42
+ def create_transaction!(transaction, options = {})
43
+ tx_blob = sign_transaction(transaction, options)
44
+ client.json_rpc(:submit, [tx_blob]).yield_self do |result|
45
+ error_message = {
46
+ message: result.fetch('engine_result_message'),
47
+ status: result.fetch('engine_result')
48
+ }
49
+
50
+ # TODO: It returns provision results. Transaction may fail or success
51
+ # than change status to opposite one before ledger is final.
52
+ # Need to set special status and recheck this transaction status
53
+ if result['engine_result'].to_s == 'tesSUCCESS' && result['status'].to_s == 'success'
54
+ transaction.hash = result.fetch('tx_json').fetch('hash')
55
+ else
56
+ raise Error, "XRP withdrawal from #{@wallet.fetch(:address)} to #{transaction.to_address} failed. Message: #{error_message}."
57
+ end
58
+ transaction
59
+ end
60
+ end
61
+
62
+ def sign_transaction(transaction, options = {})
63
+ account_address = normalize_address(@wallet[:address])
64
+ destination_address = normalize_address(transaction.to_address)
65
+ destination_tag = destination_tag_from(transaction.to_address)
66
+ fee = calculate_current_fee
67
+
68
+ amount = convert_to_base_unit(transaction.amount)
69
+
70
+ # Subtract fees from initial deposit amount in case of deposit collection
71
+ amount -= fee if options.dig(:subtract_fee)
72
+ transaction.amount = convert_from_base_unit(amount) unless transaction.amount == amount
73
+
74
+ params = [{
75
+ secret: @wallet.fetch(:secret),
76
+ tx_json: {
77
+ Account: account_address,
78
+ Amount: amount.to_s,
79
+ Fee: fee.to_s,
80
+ Destination: destination_address,
81
+ DestinationTag: destination_tag,
82
+ TransactionType: 'Payment',
83
+ LastLedgerSequence: latest_block_number + 4
84
+ }
85
+ }]
86
+
87
+ client.json_rpc(:sign, params).yield_self do |result|
88
+ if result['status'].to_s == 'success'
89
+ { tx_blob: result['tx_blob'] }
90
+ else
91
+ raise Error, "XRP sign transaction from #{account_address} to #{destination_address} failed: #{result}."
92
+ end
93
+ end
94
+ end
95
+
96
+ # Returns fee in drops that is enough to process transaction in current ledger
97
+ def calculate_current_fee
98
+ client.json_rpc(:fee, {}).yield_self do |result|
99
+ result.dig('drops', 'open_ledger_fee').to_i
100
+ end
101
+ end
102
+
103
+ def latest_block_number
104
+ client.json_rpc(:ledger, [{ ledger_index: 'validated' }]).fetch('ledger_index')
105
+ rescue Client::Error => e
106
+ raise Peatio::Blockchain::ClientError, e
107
+ end
108
+
109
+ def load_balance!
110
+ client.json_rpc(:account_info,
111
+ [account: normalize_address(@wallet.fetch(:address)), ledger_index: 'validated', strict: true])
112
+ .fetch('account_data')
113
+ .fetch('Balance')
114
+ .to_d
115
+ .yield_self { |amount| convert_from_base_unit(amount) }
116
+
117
+ rescue Client::Error => e
118
+ raise Peatio::Wallet::ClientError, e
119
+ end
120
+
121
+ private
122
+
123
+ def destination_tag_from(address)
124
+ address =~ /\?dt=(\d*)\Z/
125
+ $1.to_i
126
+ end
127
+
128
+ def normalize_address(address)
129
+ address.gsub(/\?dt=\d*\Z/, '')
130
+ end
131
+
132
+ def convert_from_base_unit(value)
133
+ value.to_d / @currency.fetch(:base_factor).to_d
134
+ end
135
+
136
+ def convert_to_base_unit(value)
137
+ x = value.to_d * @currency.fetch(:base_factor)
138
+ unless (x % 1).zero?
139
+ raise Peatio::Ripple::Wallet::Error,
140
+ "Failed to convert value to base (smallest) unit because it exceeds the maximum precision: " \
141
+ "#{value.to_d} - #{x.to_d} must be equal to zero."
142
+ end
143
+ x.to_i
144
+ end
145
+
146
+ def client
147
+ uri = @wallet.fetch(:uri) { raise Peatio::Wallet::MissingSettingError, :uri }
148
+ @client ||= Client.new(uri)
149
+ end
150
+ end
151
+ end
152
+ end
@@ -0,0 +1,38 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "peatio/ripple/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "peatio-ripple"
8
+ spec.version = Peatio::Ripple::VERSION
9
+ spec.authors = ["Maksym N."]
10
+ spec.email = ["mnaichuk@heliostech.fr"]
11
+
12
+ spec.summary = %q{Gem for extending Peatio plugable system with Ripple implementation.}
13
+ spec.description = %q{Ripple Peatio gem which implements Peatio::Blockchain::Abstract & Peatio::Wallet::Abstract.}
14
+ spec.homepage = "https://openware.com/"
15
+ spec.license = "MIT"
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ end
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.add_dependency "activesupport", "~> 5.2.3"
27
+ spec.add_dependency "peatio", "~> 0.6.1"
28
+ spec.add_dependency "faraday", "~> 0.15.4"
29
+ spec.add_dependency "memoist", "~> 0.16.0"
30
+ spec.add_dependency "better-faraday", "~> 1.0.5"
31
+
32
+ spec.add_development_dependency "bundler", "~> 1.17"
33
+ spec.add_development_dependency "rake", "~> 10.0"
34
+ spec.add_development_dependency "rspec", "~> 3.0"
35
+ spec.add_development_dependency "mocha", "~> 1.8"
36
+ spec.add_development_dependency "pry-byebug"
37
+ spec.add_development_dependency "webmock", "~> 3.5"
38
+ end
metadata ADDED
@@ -0,0 +1,222 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: peatio-ripple
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Maksym N.
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-07-31 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 5.2.3
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 5.2.3
27
+ - !ruby/object:Gem::Dependency
28
+ name: peatio
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.6.1
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.6.1
41
+ - !ruby/object:Gem::Dependency
42
+ name: faraday
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 0.15.4
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 0.15.4
55
+ - !ruby/object:Gem::Dependency
56
+ name: memoist
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 0.16.0
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 0.16.0
69
+ - !ruby/object:Gem::Dependency
70
+ name: better-faraday
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 1.0.5
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 1.0.5
83
+ - !ruby/object:Gem::Dependency
84
+ name: bundler
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.17'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.17'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rake
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '10.0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '10.0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rspec
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '3.0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '3.0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: mocha
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: '1.8'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: '1.8'
139
+ - !ruby/object:Gem::Dependency
140
+ name: pry-byebug
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: '0'
153
+ - !ruby/object:Gem::Dependency
154
+ name: webmock
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - "~>"
158
+ - !ruby/object:Gem::Version
159
+ version: '3.5'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - "~>"
165
+ - !ruby/object:Gem::Version
166
+ version: '3.5'
167
+ description: Ripple Peatio gem which implements Peatio::Blockchain::Abstract & Peatio::Wallet::Abstract.
168
+ email:
169
+ - mnaichuk@heliostech.fr
170
+ executables: []
171
+ extensions: []
172
+ extra_rdoc_files: []
173
+ files:
174
+ - ".gitignore"
175
+ - ".rspec"
176
+ - ".travis.yml"
177
+ - Gemfile
178
+ - Gemfile.lock
179
+ - LICENSE.txt
180
+ - README.md
181
+ - Rakefile
182
+ - bin/console
183
+ - bin/setup
184
+ - config/blockchains.yml
185
+ - config/currencies.yml
186
+ - config/wallets.yml
187
+ - docs/integration.md
188
+ - docs/json-rpc.md
189
+ - docs/testnet.md
190
+ - lib/peatio/ripple.rb
191
+ - lib/peatio/ripple/blockchain.rb
192
+ - lib/peatio/ripple/client.rb
193
+ - lib/peatio/ripple/hooks.rb
194
+ - lib/peatio/ripple/password_generator.rb
195
+ - lib/peatio/ripple/railtie.rb
196
+ - lib/peatio/ripple/version.rb
197
+ - lib/peatio/ripple/wallet.rb
198
+ - peatio-ripple.gemspec
199
+ homepage: https://openware.com/
200
+ licenses:
201
+ - MIT
202
+ metadata: {}
203
+ post_install_message:
204
+ rdoc_options: []
205
+ require_paths:
206
+ - lib
207
+ required_ruby_version: !ruby/object:Gem::Requirement
208
+ requirements:
209
+ - - ">="
210
+ - !ruby/object:Gem::Version
211
+ version: '0'
212
+ required_rubygems_version: !ruby/object:Gem::Requirement
213
+ requirements:
214
+ - - ">="
215
+ - !ruby/object:Gem::Version
216
+ version: '0'
217
+ requirements: []
218
+ rubygems_version: 3.0.3
219
+ signing_key:
220
+ specification_version: 4
221
+ summary: Gem for extending Peatio plugable system with Ripple implementation.
222
+ test_files: []