Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions lib/pinetwork.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ class PiNetwork
BASE_URL = "https://api.minepi.com".freeze
MAINNET_HOST = "api.mainnet.minepi.com".freeze
TESTNET_HOST = "api.testnet.minepi.com".freeze
TX_SUBMISSION_TIMEOUT_SECONDS = 30
TX_RETRY_DELAY_SECONDS = 5

def initialize(api_key:, wallet_private_key:, faraday: Faraday.new, options: {})
validate_private_seed_format!(wallet_private_key)
Expand Down Expand Up @@ -56,7 +58,7 @@ def create_payment(payment_data)
)

parsed_response = handle_http_response(response, "An unknown error occurred while creating a payment")

identifier = parsed_response["identifier"]
@open_payments_mutex.synchronize do
@open_payments[identifier] = parsed_response
Expand Down Expand Up @@ -161,7 +163,7 @@ def handle_http_response(response, unknown_error_message = "An unknown error occ
end

def set_horizon_client(network)
host = (network.starts_with? "Pi Network") ? @mainnet_host : @testnet_host
host = (network.start_with? "Pi Network") ? @mainnet_host : @testnet_host
horizon = "https://#{host}"

client = Stellar::Horizon::Client.new(host: host, horizon: horizon)
Expand All @@ -176,7 +178,7 @@ def load_account(private_seed)

def build_a2u_transaction(transaction_data)
raise StandardError.new("You should use a private seed of your app wallet!") if self.from_address != self.account.address

validate_payment_data!(transaction_data, {amount: true, identifier: true, recipient: true})

amount = Stellar::Amount.new(transaction_data[:amount])
Expand All @@ -185,28 +187,66 @@ def build_a2u_transaction(transaction_data)
recipient = Stellar::KeyPair.from_address(transaction_data[:recipient])
memo = Stellar::Memo.new(:memo_text, transaction_data[:identifier])

# Add time_bounds so we can place a time limit on the transaction and try the same
# one multiple times (in case of Horizon server errors)
min_time = Time.now.utc.to_i
max_time = min_time + TX_SUBMISSION_TIMEOUT_SECONDS
time_bounds = Stellar::TimeBounds.new(min_time:, max_time:)

payment_operation = Stellar::Operation.payment(destination: recipient, amount: amount.to_payment)

my_public_key = self.account.address
sequence_number = self.client.account_info(my_public_key).sequence.to_i
transaction_builder = Stellar::TransactionBuilder.new(
source_account: self.account.keypair,
sequence_number: sequence_number + 1,
base_fee: fee,
memo: memo
memo: memo,
time_bounds: time_bounds
)

transaction = transaction_builder.add_operation(payment_operation).set_timeout(180000).build
transaction = transaction_builder.add_operation(payment_operation).build
end

def parse_horizon_error_response(body)
result_codes = body&.dig("extras", "result_codes")
tx_error_code = result_codes&.dig("transaction") || "unknown"
op_error_code = result_codes&.dig("operations") || "unknown"

return tx_error_code, op_error_code
end

def submit_transaction(transaction)
envelope = transaction.to_envelope(self.account.keypair)
begin
response = self.client.submit_transaction(tx_envelope: envelope)
txid = response._response.body["id"]

return txid if txid.present?

status = response._response.status
error_type = status / 100 # 4 == client-side error; 5 == server-side error

if error_type == 4 # Raise the error immediately; something is wrong on our end
tx_error_code, op_error_code = parse_horizon_error_response(response._response.body)
raise Errors::TxSubmissionError.new(tx_error_code, op_error_code)
elsif error_type != 5 # Some unexpected_status_code
# Repurposing TxSubmissionError here so we don't have to make a new Error for an unlikely response to encounter
raise Errors::TxSubmissionError.new("unexpected_response_code", [status])
end

# Server-side error
# Wait a moment, then try the tx again
# If we're past the time bounds we'll receive a 400 response and raise an exception
sleep TX_RETRY_DELAY_SECONDS

submit_transaction(transaction)
rescue Errors::TxSubmissionError => error
# No need to parse the response if we already formatted the exception in the `begin` block
raise error
rescue => error
result_codes = error.response&.dig(:body, "extras", "result_codes")
raise Errors::TxSubmissionError.new(result_codes&.dig("transaction"), result_codes&.dig("operations"))
tx_error_code, op_error_code = parse_horizon_error_response(error&.response&.dig(:body))
raise Errors::TxSubmissionError.new(tx_error_code, op_error_code)
end
end

Expand All @@ -227,4 +267,4 @@ def validate_private_seed_format!(seed)
def extract_error_message(response_body, default_message)
JSON.parse(response_body).dig("error_message") rescue default_message
end
end
end
7 changes: 5 additions & 2 deletions pinetwork.gemspec
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
Gem::Specification.new do |s|
s.name = "pinetwork"
s.version = "0.1.5"
s.version = "0.1.6"
s.summary = "Pi Network Ruby"
s.description = "Pi Network backend library for Ruby-based webservers."
s.description = "Pi Network backend library for Ruby-based web servers."
s.authors = ["Pi Core Team"]
s.email = "support@minepi.com"
s.files = [
"lib/pinetwork.rb",
"lib/errors.rb",
"test/a2u_concurrency_test.rb",
"test/transaction_submission_test.rb",
"Rakefile"
]
s.homepage = "https://github.com/pi-apps/pi-ruby"
s.license = "PiOS"
s.add_runtime_dependency "stellar-sdk", "~> 0.31.0"
s.add_runtime_dependency "faraday", "~> 1.6.0"
s.add_development_dependency "minitest", "~> 5.25.4"
s.add_development_dependency "mocha", "~> 2.7.1"
s.metadata = {
"documentation_uri" => "https://github.com/pi-apps/pi-ruby",
}
Expand Down
8 changes: 4 additions & 4 deletions test/a2u_concurrency_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ class A2UConcurrencyTest < Minitest::Test
def test_concurrent_create_payment
total_threads = 10000
api_key = "api-key"
wallet_private_key = "SC2L62EYF7LYF43L4OOSKUKDESRAFJZW3UW6RFZ57UY25VAMHTL2BFER"
wallet_private_key = Stellar::KeyPair.random.seed

threads = []

faraday_stub = Minitest::Mock.new
pi = PiNetwork.new(api_key: api_key, wallet_private_key: wallet_private_key, faraday: faraday_stub)

Expand All @@ -22,7 +22,7 @@ def test_concurrent_create_payment
faraday_stub.expect(:post, faraday_response) do |url|
url == "https://api.minepi.com/v2/payments"
end

payment_data = { amount: 1, memo: "test", metadata: {"info": "test"}, uid: "test-uid" }
payment_id = pi.create_payment(payment_data)
end
Expand All @@ -32,4 +32,4 @@ def test_concurrent_create_payment
open_payments_after = pi.instance_variable_get(:@open_payments)
assert_equal(total_threads, open_payments_after.values.uniq.count, "open_payments got corrupted!")
end
end
end
115 changes: 115 additions & 0 deletions test/transaction_submission_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
require 'minitest/autorun'
require 'mocha/minitest'
require 'ostruct'
require_relative '../lib/pinetwork'
require_relative '../lib/errors'

def set_tx_submission_timers(timeout, retry_delay)
# Disable warnings that will clog up the terminal
$VERBOSE = nil

PiNetwork.const_set(:TX_SUBMISSION_TIMEOUT_SECONDS, timeout)
PiNetwork.const_set(:TX_RETRY_DELAY_SECONDS, retry_delay)

$VERBOSE = true
end

def json_parse_to_struct(hash)
JSON.parse(hash.to_json, { object_class: OpenStruct })
end

def setup_horizon_mock(submit_transaction_response_hashes)
horizon_mock = mock()

account_info_response = OpenStruct.new(sequence: 1) # Used during build_a2u_transaction
horizon_mock.expects(:account_info).returns(account_info_response).at_least_once

submit_transaction_responses = submit_transaction_response_hashes.map { |h| json_parse_to_struct(h) }
horizon_mock.expects(:submit_transaction).returns(*submit_transaction_responses).at_least_once

horizon_mock
end

class TransactionSubmissionTest < Minitest::Test
attr_reader :pi, :account, :payment, :txid

def setup
# Adjust submission timeout values to speed the test up
set_tx_submission_timers(5, 1)

# Then set up the necessary data
api_key = "api-key"
wallet_private_key = Stellar::KeyPair.random.seed
@pi = PiNetwork.new(api_key: api_key, wallet_private_key: wallet_private_key)

from_wallet_keypair = Stellar::KeyPair.from_seed(wallet_private_key)
from_address = from_wallet_keypair.public_key
@account = OpenStruct.new(address: from_address, keypair: from_wallet_keypair)

payment_id = "1234abcd"
@payment = {
"identifier" => payment_id,
"network" => "Pi Network",
"amount" => 3.14,
"from_address" => account.address,
"to_address" => Stellar::KeyPair.random.address
}

@txid = "01234abcde"

pi.stubs(:get_payment).returns(payment) # Avoid API call to platform BE
pi.stubs(:account).returns(account)
end

def teardown
set_tx_submission_timers(30, 5)
end

def test_server_error_response
submit_transaction_responses = [
{ _response: { body: { title: "Historical DB Is Too Stale" }, status: 503 } }, # Server error response first
{ _response: { body: { "id": txid }, status: 200 } } # Then success on retry
]
horizon_mock = setup_horizon_mock(submit_transaction_responses)

pi.stubs(:client).returns(horizon_mock)

assert_equal(txid, pi.submit_payment(payment["identifier"]), "Returned txid does not match expected value")
end

def test_user_error_response
submit_transaction_responses = [
{
_response: {
body: {
title: "Transaction Failed",
extras: {
result_codes: {
transaction: "tx_failed",
operations: ["op_no_source_account"]
}
}
},
status: 400
}
}
]
horizon_mock = setup_horizon_mock(submit_transaction_responses)

pi.stubs(:client).returns(horizon_mock)

error = assert_raises(PiNetwork::Errors::TxSubmissionError) { pi.submit_payment(payment["identifier"]) }

assert_equal("tx_failed", error.tx_error_code, "Raised error has wrong tx error code")
assert_equal(["op_no_source_account"], error.op_error_codes, "Raised error has wrong op error codes")
end

def test_success_response
submit_transaction_responses = [{ _response: { body: { "id": txid }, status: 200 } }]
horizon_mock = setup_horizon_mock(submit_transaction_responses)

pi.stubs(:client).returns(horizon_mock)

assert_equal(txid, pi.submit_payment(payment["identifier"]), "Returned txid does not match expected value")
end
end