innox 2.7.6

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 (53) hide show
  1. checksums.yaml +7 -0
  2. data/.drone.yml +29 -0
  3. data/.gitattributes +2 -0
  4. data/.gitignore +16 -0
  5. data/.rspec +3 -0
  6. data/.rubocop.yml +148 -0
  7. data/.simplecov +17 -0
  8. data/.travis.yml +18 -0
  9. data/Gemfile +8 -0
  10. data/Gemfile.lock +190 -0
  11. data/README.md +25 -0
  12. data/Rakefile +6 -0
  13. data/bin/console +14 -0
  14. data/bin/innox +12 -0
  15. data/bin/setup +8 -0
  16. data/checksums.yaml +7 -0
  17. data/innox.gemspec +52 -0
  18. data/lib/innox/adapter_registry.rb +25 -0
  19. data/lib/innox/auth/error.rb +18 -0
  20. data/lib/innox/auth/jwt_authenticator.rb +127 -0
  21. data/lib/innox/block.rb +27 -0
  22. data/lib/innox/blockchain/abstract.rb +159 -0
  23. data/lib/innox/blockchain/error.rb +37 -0
  24. data/lib/innox/blockchain/registry.rb +16 -0
  25. data/lib/innox/command/base.rb +11 -0
  26. data/lib/innox/command/db.rb +20 -0
  27. data/lib/innox/command/inject.rb +13 -0
  28. data/lib/innox/command/root.rb +14 -0
  29. data/lib/innox/command/security.rb +29 -0
  30. data/lib/innox/command/service.rb +40 -0
  31. data/lib/innox/error.rb +18 -0
  32. data/lib/innox/executor.rb +64 -0
  33. data/lib/innox/injectors/innox_events.rb +240 -0
  34. data/lib/innox/logger.rb +39 -0
  35. data/lib/innox/metrics/server.rb +15 -0
  36. data/lib/innox/mq/client.rb +51 -0
  37. data/lib/innox/ranger/connection.rb +117 -0
  38. data/lib/innox/ranger/events.rb +11 -0
  39. data/lib/innox/ranger/router.rb +234 -0
  40. data/lib/innox/ranger/web_socket.rb +68 -0
  41. data/lib/innox/security/key_generator.rb +26 -0
  42. data/lib/innox/sql/client.rb +19 -0
  43. data/lib/innox/sql/schema.rb +72 -0
  44. data/lib/innox/transaction.rb +136 -0
  45. data/lib/innox/upstream/base.rb +116 -0
  46. data/lib/innox/upstream/registry.rb +14 -0
  47. data/lib/innox/version.rb +3 -0
  48. data/lib/innox/wallet/abstract.rb +188 -0
  49. data/lib/innox/wallet/error.rb +37 -0
  50. data/lib/innox/wallet/registry.rb +16 -0
  51. data/lib/innox.rb +47 -0
  52. data/metadata +463 -0
  53. metadata +465 -0
@@ -0,0 +1,127 @@
1
+ require "jwt"
2
+
3
+ require_relative "error"
4
+
5
+ module Innox::Auth
6
+ # JWTAuthenticator used to authenticate user using JWT.
7
+ #
8
+ # It allows configuration of JWT verification through following ENV
9
+ # variables (all optional):
10
+ # * JWT_ISSUER
11
+ # * JWT_AUDIENCE
12
+ # * JWT_ALGORITHM (default: RS256)
13
+ # * JWT_DEFAULT_LEEWAY
14
+ # * JWT_ISSUED_AT_LEEWAY
15
+ # * JWT_EXPIRATION_LEEWAY
16
+ # * JWT_NOT_BEFORE_LEEWAY
17
+ #
18
+ # @see https://github.com/jwt/ruby-jwt JWT validation parameters.
19
+ #
20
+ # @example Token validation
21
+ # rsa_private = OpenSSL::PKey::RSA.generate(2048)
22
+ # rsa_public = rsa_private.public_key
23
+ #
24
+ # payload = {
25
+ # iat: Time.now.to_i,
26
+ # exp: (Time.now + 60).to_i,
27
+ # sub: "session",
28
+ # iss: "contour",
29
+ # aud: [
30
+ # "innox",
31
+ # "contour",
32
+ # ],
33
+ # jti: "BEF5617B7B2762DDE61702F5",
34
+ # uid: "TEST123",
35
+ # email: "user@example.com",
36
+ # role: "admin",
37
+ # level: 4,
38
+ # state: "active",
39
+ # }
40
+ #
41
+ # token = JWT.encode(payload, rsa_private, "RS256")
42
+ #
43
+ # auth = Innox::Auth::JWTAuthenticator.new(rsa_public)
44
+ # auth.authenticate!("Bearer #{token}")
45
+ class JWTAuthenticator
46
+ # Creates new authenticator with given public key.
47
+ #
48
+ # @param public_key [OpenSSL::PKey::PKey] Public key object to verify
49
+ # signature.
50
+ # @param private_key [OpenSSL::PKey::PKey] Optional private key that used
51
+ # only to encode new tokens.
52
+ def initialize(public_key, private_key = nil)
53
+ @public_key = public_key
54
+ @private_key = private_key
55
+
56
+ @verify_options = {
57
+ verify_expiration: true,
58
+ verify_not_before: true,
59
+ iss: ENV["JWT_ISSUER"],
60
+ verify_iss: !ENV["JWT_ISSUER"].nil?,
61
+ verify_iat: true,
62
+ verify_jti: true,
63
+ aud: ENV["JWT_AUDIENCE"].to_s.split(",").reject(&:empty?),
64
+ verify_aud: !ENV["JWT_AUDIENCE"].nil?,
65
+ sub: "session",
66
+ verify_sub: true,
67
+ algorithms: [ENV["JWT_ALGORITHM"] || "RS256"],
68
+ leeway: ENV["JWT_DEFAULT_LEEWAY"].yield_self { |n| n.to_i unless n.nil? },
69
+ iat_leeway: ENV["JWT_ISSUED_AT_LEEWAY"].yield_self { |n| n.to_i unless n.nil? },
70
+ exp_leeway: ENV["JWT_EXPIRATION_LEEWAY"].yield_self { |n| n.to_i unless n.nil? },
71
+ nbf_leeway: ENV["JWT_NOT_BEFORE_LEEWAY"].yield_self { |n| n.to_i unless n.nil? },
72
+ }.compact
73
+
74
+ @encode_options = {
75
+ algorithm: @verify_options[:algorithms].first,
76
+ }.compact
77
+ end
78
+
79
+ # Decodes and verifies JWT.
80
+ # Returns payload from JWT or raises an exception
81
+ #
82
+ # @param token [String] Token string. Must start from <tt>"Bearer "</tt>.
83
+ # @return [Hash] Payload Hash from JWT without any changes.
84
+ #
85
+ # @raise [Innox::Auth::Error] If token is invalid or can't be verified.
86
+ def authenticate!(token)
87
+ token_type, token_value = token.to_s.split(" ")
88
+
89
+ unless token_type == "Bearer"
90
+ raise(Innox::Auth::Error, "Token type is not provided or invalid.")
91
+ end
92
+
93
+ decode_and_verify_token(token_value)
94
+ rescue => error
95
+ case error
96
+ when Innox::Auth::Error
97
+ raise(error)
98
+ else
99
+ raise(Innox::Auth::Error, error.message)
100
+ end
101
+ end
102
+
103
+ # Encodes given payload and produces JWT.
104
+ #
105
+ # @param payload [String, Hash] Payload to encode.
106
+ # @return [String] JWT token string.
107
+ #
108
+ # @raise [ArgumentError] If no private key was passed to constructor.
109
+ def encode(payload)
110
+ raise(::ArgumentError, "No private key given.") if @private_key.nil?
111
+
112
+ JWT.encode(payload, @private_key, @encode_options[:algorithm])
113
+ end
114
+
115
+ private
116
+
117
+ def decode_and_verify_token(token)
118
+ payload, header = JWT.decode(token, @public_key, true, @verify_options)
119
+
120
+ payload.keys.each { |k| payload[k.to_sym] = payload.delete(k) }
121
+
122
+ payload
123
+ rescue JWT::DecodeError => e
124
+ raise(Innox::Auth::Error, "Failed to decode and verify JWT: #{e.message}")
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,27 @@
1
+ module Innox #:nodoc:
2
+
3
+ # This class represents blockchain block which contains transactions.
4
+ #
5
+ # Using instant of this class in return for Innox::Blockchain#fetch_block!
6
+ # @see Innox::Blockchain#fetch_block! example implementation
7
+ #
8
+
9
+ class Block
10
+ include Enumerable
11
+
12
+ delegate :each, to: :@transactions
13
+
14
+ # @!attribute [r] number
15
+ # return [String] block number
16
+ attr_reader :number
17
+
18
+ # @!attribute [r] transactions
19
+ # return [Array<Innox::Transaction>]
20
+ attr_reader :transactions
21
+
22
+ def initialize(number, transactions)
23
+ @number = number
24
+ @transactions = transactions
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,159 @@
1
+ module Innox #:nodoc:
2
+ module Blockchain #:nodoc:
3
+
4
+ # @abstract Represents basic blockchain interface.
5
+ #
6
+ # Subclass and override abstract methods to implement
7
+ # a innox plugable blockchain.
8
+ # Then you need to register your blockchain implementation.
9
+ #
10
+ # @see Bitcoin::Blockchain Bitcoin as example of Abstract imlementation
11
+ #
12
+ # @example
13
+ #
14
+ # class MyBlockchain < Innox::Abstract::Blockchain
15
+ # def fetch_block(block_number)
16
+ # # do something
17
+ # end
18
+ # ...
19
+ # end
20
+ #
21
+ # # Register MyBlockchain as innox plugable blockchain.
22
+ # Innox::Blockchain.registry[:my_blockchain] = MyBlockchain.new
23
+ #
24
+
25
+ class Abstract
26
+
27
+ # Hash of features supported by blockchain.
28
+ #
29
+ # @abstract
30
+ #
31
+ # @see Abstract::SUPPORTED_FEATURES for list of features supported by innox.
32
+ #
33
+ # @!attribute [r] features
34
+ # @return [Hash] list of features supported by blockchain.
35
+ attr_reader :features
36
+
37
+ # List of features supported by innox.
38
+ #
39
+ # @note Features list:
40
+ #
41
+ # case_sensitive - defines if transactions and addresses of current
42
+ # blockchain are case_sensitive.
43
+ #
44
+ # cash_addr_format - defines if blockchain supports Cash Address format
45
+ # for more info see (https://support.exodus.io/article/664-bitcoin-cash-address-format)
46
+ SUPPORTED_FEATURES = %i[case_sensitive cash_addr_format].freeze
47
+
48
+
49
+ # Current blockchain settings for performing API calls and building blocks.
50
+ #
51
+ # @abstract
52
+ #
53
+ # @see Abstract::SUPPORTED_SETTINGS for list of settings required by blockchain.
54
+ #
55
+ # @!attribute [r] settings
56
+ # @return [Hash] current blockchain settings.
57
+ attr_reader :settings
58
+
59
+ # List of configurable settings.
60
+ #
61
+ # @see #configure
62
+ SUPPORTED_SETTINGS = %i[server currencies].freeze
63
+
64
+
65
+ # Abstract constructor.
66
+ #
67
+ # @abstract
68
+ #
69
+ # @example
70
+ # class MyBlockchain < Innox::Abstract::Blockchain
71
+ #
72
+ # DEFAULT_FEATURES = {case_sensitive: true, cash_addr_format: false}.freeze
73
+ #
74
+ # # You could override default features by passing them to initializer.
75
+ # def initialize(my_custom_features = {})
76
+ # @features = DEFAULT_FEATURES.merge(my_custom_features)
77
+ # end
78
+ # ...
79
+ # end
80
+ #
81
+ # # Register MyBlockchain as innox plugable blockchain.
82
+ # custom_features = {cash_addr_format: true}
83
+ # Innox::Blockchain.registry[:my_blockchain] = MyBlockchain.new(custom_features)
84
+ def initialize(*)
85
+ abstract_method
86
+ end
87
+
88
+ # Merges given configuration parameters with defined during initialization
89
+ # and returns the result.
90
+ #
91
+ # @abstract
92
+ #
93
+ # @param [Hash] settings parameters to use.
94
+ #
95
+ # @option settings [String] :server Public blockchain API endpoint.
96
+ # @option settings [Array<Hash>] :currencies List of currency hashes
97
+ # with :id,:base_factor,:options(deprecated) keys.
98
+ # Custom keys could be added by defining them in Currency #options.
99
+ #
100
+ # @return [Hash] merged settings.
101
+ #
102
+ # @note Be careful with your blockchain state after configure.
103
+ # Clean everything what could be related to other blockchain configuration.
104
+ # E.g. client state.
105
+ def configure(settings = {})
106
+ abstract_method
107
+ end
108
+
109
+ # Fetches blockchain block by calling API and builds block object
110
+ # from response payload.
111
+ #
112
+ # @abstract
113
+ #
114
+ # @param block_number [Integer] the block number.
115
+ # @return [Innox::Block] the block object.
116
+ # @raise [Innox::Blockchain::ClientError] if error was raised
117
+ # on blockchain API call.
118
+ def fetch_block!(block_number)
119
+ abstract_method
120
+ end
121
+
122
+ # Fetches current blockchain height by calling API and returns it as number.
123
+ #
124
+ # @abstract
125
+ #
126
+ # @return [Integer] the current blockchain height.
127
+ # @raise [Innox::Blockchain::ClientError] if error was raised
128
+ # on blockchain API call.
129
+ def latest_block_number
130
+ abstract_method
131
+ end
132
+
133
+ # Fetches address balance of specific currency.
134
+ #
135
+ # @note Optional. Don't override this method if your blockchain
136
+ # doesn't provide functionality to get balance by address.
137
+ #
138
+ # @param address [String] the address for requesting balance.
139
+ # @param currency_id [String] which currency balance we need to request.
140
+ # @return [BigDecimal] the current address balance.
141
+ # @raise [Innox::Blockchain::ClientError,Innox::Blockchain::UnavailableAddressBalanceError]
142
+ # if error was raised on blockchain API call ClientError is raised.
143
+ # if blockchain API call was successful but we can't detect balance
144
+ # for address Error is raised.
145
+ def load_balance_of_address!(address, currency_id)
146
+ raise Innox::Blockchain::UnavailableAddressBalanceError
147
+ end
148
+
149
+ private
150
+
151
+ # Method for defining other methods as abstract.
152
+ #
153
+ # @raise [MethodNotImplemented]
154
+ def abstract_method
155
+ method_not_implemented
156
+ end
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,37 @@
1
+ module Innox
2
+ module Blockchain
3
+ Error = Class.new(StandardError)
4
+
5
+ class ClientError < Error
6
+
7
+ attr_reader :wrapped_ex
8
+
9
+ def initialize(ex_or_string)
10
+ @wrapped_ex = nil
11
+
12
+ if ex_or_string.respond_to?(:backtrace)
13
+ super(ex_or_string.message)
14
+ @wrapped_exception = ex_or_string
15
+ else
16
+ super(ex_or_string.to_s)
17
+ end
18
+ end
19
+ end
20
+
21
+ class MissingSettingError < Error
22
+ def initialize(key)
23
+ super "#{key.capitalize} setting is missing"
24
+ end
25
+ end
26
+
27
+ class UnavailableAddressBalanceError < Error
28
+ def initialize(address)
29
+ @address = address
30
+ end
31
+
32
+ def message
33
+ "Unable to load #{@address} balance"
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,16 @@
1
+ require "innox/adapter_registry"
2
+
3
+ module Innox
4
+ module Blockchain
5
+
6
+ VERSION = "1.0.0".freeze
7
+
8
+ class << self
9
+ def registry
10
+ @registry ||= Registry.new
11
+ end
12
+ end
13
+ class Registry < Innox::AdapterRegistry
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,11 @@
1
+ module Innox::Command
2
+ class Base < Clamp::Command
3
+ def say(str)
4
+ puts str
5
+ end
6
+
7
+ def sql_client
8
+ @sql_client ||= Innox::Sql::Client.new.connect
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,20 @@
1
+ module Innox::Command::DB
2
+ class Create < Innox::Command::Base
3
+ def execute
4
+ client = Innox::Sql::Client.new
5
+ database_name = client.config.delete(:database)
6
+ Innox::Sql::Schema.new(client.connect).create_database(database_name)
7
+ end
8
+ end
9
+
10
+ class Migrate < Innox::Command::Base
11
+ def execute
12
+ Innox::Sql::Schema.new(sql_client).create_tables
13
+ end
14
+ end
15
+
16
+ class Root < Innox::Command::Base
17
+ subcommand "create", "Create database", Innox::Command::DB::Create
18
+ subcommand "migrate", "Create tables", Innox::Command::DB::Migrate
19
+ end
20
+ end
@@ -0,0 +1,13 @@
1
+ module Innox::Command
2
+ class Inject < Innox::Command::Base
3
+ class InnoxEvents < Innox::Command::Base
4
+ option ["-e", "--exchange"], "NAME", "exchange name to inject messages to", default: "innox.events.ranger"
5
+ def execute
6
+ Innox::Logger.logger.level = :debug
7
+ Innox::Injectors::InnoxEvents.new.run!(exchange)
8
+ end
9
+ end
10
+
11
+ subcommand "innox_events", "Inject innox events in mq", InnoxEvents
12
+ end
13
+ end
@@ -0,0 +1,14 @@
1
+ require "innox/command/base"
2
+ require "innox/command/service"
3
+ require "innox/command/db"
4
+ require "innox/command/inject"
5
+ require "innox/command/security"
6
+
7
+ module Innox
8
+ class Root < Command::Base
9
+ subcommand "db", "Database related sub-commands", Innox::Command::DB::Root
10
+ subcommand "service", "Services management related sub-commands", Innox::Command::Service::Root
11
+ subcommand "inject", "Data injectors", Innox::Command::Inject
12
+ subcommand "security", "Security management related sub-commands", Innox::Command::Security
13
+ end
14
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Innox::Command
4
+ class Security < Innox::Command::Base
5
+ class KeyGenerator < Innox::Command::Base
6
+ option "--print", :flag, "print on screen"
7
+ option "--path", "FOLDER", "save keypair into folder", default: "secrets"
8
+
9
+ def execute
10
+ keypair = Innox::Security::KeyGenerator.new
11
+
12
+ if print?
13
+ puts keypair.private, keypair.public
14
+ puts "-----BASE64 ENCODED-----"
15
+ puts Base64.urlsafe_encode64(keypair.public)
16
+ else
17
+ begin
18
+ keypair.save(path)
19
+ puts "Files saved in #{File.join(path, 'rsa-key')}"
20
+ rescue IOError => e
21
+ abort("Failed saving files")
22
+ end
23
+ end
24
+ end
25
+ end
26
+
27
+ subcommand "keygen", "Generate a public private rsa key pair", KeyGenerator
28
+ end
29
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Innox::Command::Service
4
+ class Start < Innox::Command::Base
5
+ class Ranger < Innox::Command::Base
6
+ option ["-e", "--exchange"], "NAME", "exchange name to inject messages to", default: "innox.events.ranger"
7
+ option "--[no-]stats", :flag, "display periodically connections statistics", default: true
8
+ option "--stats-period", "SECONDS", "period of displaying stats in seconds", default: 30
9
+ def execute
10
+ raise ArgumentError, "JWT_PUBLIC_KEY was not specified." if ENV["JWT_PUBLIC_KEY"].to_s.empty?
11
+
12
+ key_decoded = Base64.urlsafe_decode64(ENV["JWT_PUBLIC_KEY"])
13
+
14
+ jwt_public_key = OpenSSL::PKey.read(key_decoded)
15
+ if jwt_public_key.private?
16
+ raise ArgumentError, "JWT_PUBLIC_KEY was set to private key, however it should be public."
17
+ end
18
+
19
+ raise "stats period missing" if stats? && !stats_period
20
+
21
+ Prometheus::Client.config.data_store = Prometheus::Client::DataStores::SingleThreaded.new()
22
+ registry = Prometheus::Client.registry
23
+
24
+ opts = {
25
+ display_stats: stats?,
26
+ stats_period: stats_period.to_f,
27
+ metrics_port: 8082,
28
+ registry: registry
29
+ }
30
+ ::Innox::Ranger.run!(jwt_public_key, exchange, opts)
31
+ end
32
+ end
33
+
34
+ subcommand "ranger", "Start ranger process", Ranger
35
+ end
36
+
37
+ class Root < Innox::Command::Base
38
+ subcommand "start", "Start a service", Start
39
+ end
40
+ end
@@ -0,0 +1,18 @@
1
+ class Innox::Error < ::StandardError
2
+ @@default_code = 2000
3
+
4
+ attr :code, :text
5
+
6
+ def initialize(opts = {})
7
+ @code = opts[:code] || @@default_code
8
+ @text = opts[:text] || ""
9
+
10
+ @message = {error: {code: @code, message: @text}}
11
+
12
+ if @text != ""
13
+ super("#{@code}: #{text}")
14
+ else
15
+ super("#{@code}")
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,64 @@
1
+ require "mysql2"
2
+ require "benchmark"
3
+
4
+ client = Mysql2::Client.new(
5
+ host: "172.19.0.3",
6
+ username: "root",
7
+ password: "changeme",
8
+ port: 3306,
9
+ database: "innox_development")
10
+
11
+ queries = [
12
+ "INSERT INTO `trades` (`ask_id`, `ask_member_id`, `bid_id`, `bid_member_id`, `price`, `volume`, `funds`, `market_id`, `trend`, `created_at`, `updated_at`) VALUES (18711, 81, 18708, 82, 0.99999999, 50.0, 49.9999995, 'eurusd', 0, NOW(), NOW())",
13
+ "UPDATE `accounts` SET `accounts`.`locked` = 3571.09999702 WHERE `accounts`.`id` = 164",
14
+ "UPDATE `accounts` SET `accounts`.`balance` = 999995119.5335 WHERE `accounts`.`id` = 163",
15
+ "UPDATE `accounts` SET `accounts`.`locked` = 4257.0 WHERE `accounts`.`id` = 161",
16
+ "UPDATE `accounts` SET `accounts`.`balance` = 999995825.720262199325 WHERE `accounts`.`id` = 162",
17
+ "UPDATE `orders` SET `volume` = 20.0, `locked` = 19.9999998, `funds_received` = 53.0, `trades_count` = 2, `updated_at` = '2018-06-25 23:44:37' WHERE `orders`.`id` = 18708",
18
+ "UPDATE `orders` SET `volume` = 0.0, `locked` = 0.0, `funds_received` = 78.59999924, `trades_count` = 2, `state` = 200, `updated_at` = '2018-06-25 23:44:37' WHERE `orders`.`id` = 18711"
19
+ ]
20
+
21
+ puts Benchmark.measure {
22
+ 1_000.times {
23
+
24
+ client.query("begin")
25
+ begin
26
+
27
+ 100.times {
28
+ queries.each do |q|
29
+ client.query q
30
+ end
31
+ }
32
+
33
+ rescue Mysql2::Error => e
34
+ puts "+++++++ DB ERROR - ROLLING BACK ++++++++"
35
+ puts e
36
+ client.query("rollback")
37
+ exit
38
+ end
39
+ client.query("commit") #commit the changes to the DB
40
+
41
+ }
42
+ }
43
+
44
+ client.close
45
+
46
+ __END__
47
+
48
+ require 'mysql2/em'
49
+
50
+ EM.run do
51
+ client = Mysql2::EM::Client.new(
52
+ :host => '172.19.0.3',
53
+ :username => 'root',
54
+ :password => 'changeme',
55
+ :port => 3306,
56
+ :database => 'innox_development')
57
+
58
+
59
+ defer1 = client.query "SELECT sleep(3) as first_query"
60
+ defer1.callback do |result|
61
+ puts "Result: #{result.to_a.inspect}"
62
+ end
63
+
64
+ end