blockchain

Blockchain: Stellar Bridge Server

Stellar.org punya bridge server, yang membuat federation dan compliance server lebih mudah digunakan untuk mengirim dan menerima payments. Ketika menggunakan bridge server, code yang kita perlukan hanya adalah private service untuk menerima notifikasi payment dan me-respon pengecekakan regulator dari bridge dan compliance servers.
Payment flow diagram

Ketika menggunakan bridge server, kita mengirim payment dengan membuat request HTTP POST langsung kepadanya dan bukan ke Horizon. Ini tidak mengubah banyak pada transaksi yang sederhana, tapi akan jauh lebih mudah ketika kita sudah menggunakan  federation dan compliance server.

Buat Database

Bridge server perlu database MySQL atau PostgreSQL untuk melacak dan menkordinasikan informasi transaction dan compliance. Buat database kosong namanya stellar_bridgedan user untuk menaksesnya. Tidak perlu buat tabel apapun. Bridge punya  perintah untuk itu.

Download dan Konfigurasi Bridge Server

Lanjut, download versi terakhir bridge server untuk OS kita. Install di folder manapun yang kita mau. Di dalam folder yang sama, buat file yang namanya  bridge.cfg. File ini akan menyimpan configuration bridge server. Isinya seperti ini:

port = 8006
horizon = "https://horizon-testnet.stellar.org"
network_passphrase = "Test SDF Network ; September 2015"
# We'll fill this in once we set up a compliance server
compliance = ""

# This describes the assets that can be sent and received.
# Repeat this section to add support for more asset types.
[[assets]]
code="USD"
issuer="GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ"

[database]
type = "mysql"  # or "postgres" if you created a postgres database
url = "dbuser:dbpassword@/stellar_bridge"

[accounts]
# The secret seed for your base account, from which payments are made
base_seed = "SAV75E2NK7Q5JZZLBBBNUPCIAKABN64HNHMDLD62SZWM6EBJ4R7CUNTZ"
# The account ID that receives payments on behalf of your customers. In this
# case, it is the account ID that matches `base_seed` above.
receiving_account_id = "GAIGZHHWK3REZQPLQX5DNUN4A32CSEONTU6CMDBO7GDWLPSXZDSYA4BU"
# A secret seed that can authorize trustlines for assets you issue. For more,
# see https://stellar.org/developers/guides/concepts/assets.html#controlling-asset-holders
authorizing_seed = "SBILUHQVXKTLPYXHHBL4IQ7ISJ3AKDTI2ZC56VQ6C2BDMNF463EON65U"
# The ID of the account that issues your assets
issuing_account_id = "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ"

[callbacks]
# The server will send POST requests to this URL to notify you of payments
receive = "http://localhost:8005/receive"

Jalankan Server

Sebelum menjalankan server perlu dibuatkan tabel database terlebih dahulu. Jalankan bridge server dengan argumen --migrate-db akan membuat tabel yang diperlukan:

./bridge --migrate-db

Setiap kali kita upgrade server ke versi yang lebih baru, kita perlu jalankan command ini lagi untuk memastikan struktur tabel sesuai dengan versi tersebut..

Setelah semua ok, jalankan server dengan perintah:

./bridge

Mengirim Payment

Bridge server menerima command dalam bentuk request HTTP, jadi kita bisa coba men-submit payment dengan mengirimkan request POST ke alamat /payments. Coba kirim 1 USD ke account GCFXHS4GXL6BVUCXBWXGTITROWLVYXQKQLF4YH5O5JT3YZXCYPAFBJZB. (Ingat bahwa receiving account perlu diberi trust atas asset terlebih dahulu. Lihat pada bagian Megeluarkan Asset.)

Send a Payment
var request = require('request');

request.post({
  url: 'http://localhost:8001/payment',
  form: {
    amount: '1',
    asset_code: 'USD',
    asset_issuer: 'GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ',
    destination: 'GCFXHS4GXL6BVUCXBWXGTITROWLVYXQKQLF4YH5O5JT3YZXCYPAFBJZB',
    source: 'SAV75E2NK7Q5JZZLBBBNUPCIAKABN64HNHMDLD62SZWM6EBJ4R7CUNTZ'
  }
}, function(error, response, body) {
  if (error || response.statusCode !== 200) {
    console.error('ERROR!', error || body);
  }
  else {
    console.log('SUCCESS!', body);
  }
});

Server untuk Receive Payments

Payment flow diagram

Pada file configuration bridge server, terlihat ada callback URL bernama receive. Ketika diterima suatu payment, bridge server akan mengirim request HTTP POST ke URL yang kita tentukan disitu. Tugas utama dari receive endpoint adalah meng-update saldo customer untuk me-response transaksi penerimaan payment (karena payment awalnya masuk ke account Stellar punya kita).

Contoh implementasi Receive Callback dengan JavaScript:
/**
 * A small Express.js web server for handling payments from the bridge server.
 */

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/receive', function (request, response) {
  var payment = request.body;

  // `receive` may be called multiple times for the same payment, so check that
  // you haven't already seen this payment ID.
  if (getPaymentByIdFromDb(payment.id)) {
    return response.status(200).end();
  }

  // Because we have one Stellar account representing many customers, the
  // customer the payment is intended for should be in the transaction memo.
  var customer = getAccountFromDb(payment.memo);

  // You need to check the asset code and issuer to make sure it's an asset
  // that you can accept payment to this account for. In this example, we just
  // convert the amount to USD and adding the equivalent amount to the customer
  // balance. You need to implement `convertToUsd()` yourself.
  var dollarAmount = convertToUsd(
    payment.amount, payment.asset_code, payment.asset_issuer);
  addToBankAccountBalance(customer, dollarAmount);
  response.status(200).end();
  console.log('Added ' + dollarAmount + ' USD to account: ' + customer);
});

app.listen(8005, function () {
  console.log('Bridge server callbacks running on port 8005!');
});

Untuk memastikan bahwa receive callback bekerja dengan baik, coba kirim 1 USD ke customer Amy pada system bank kita. (Untuk detail cara mengirim payment lihat pada bagian sebelumnya)

Script test Receive Callback:
var StellarSdk = require('stellar-sdk');
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
var sourceKeys = StellarSdk.Keypair.fromSecret(
  'SCZANGBA5YHTNYVVV4C3U252E2B6P6F5T3U6MM63WBSBZATAQI3EBTQ4');
var destinationId = 'GAIGZHHWK3REZQPLQX5DNUN4A32CSEONTU6CMDBO7GDWLPSXZDSYA4BU';

server.loadAccount(sourceKeys.publicKey())
  .then(function(sourceAccount) {
    var transaction = new StellarSdk.TransactionBuilder(sourceAccount)
      .addOperation(StellarSdk.Operation.payment({
        destination: destinationId,
        asset: new StellarSdk.Asset(
          'USD', 'GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ'),
        amount: '1'
      }))
      // Use the memo to indicate the customer this payment is intended for.
      .addMemo(StellarSdk.Memo.text('Amy'))
      .build();
    transaction.sign(sourceKeys);
    return server.submitTransaction(transaction);
  })
  .then(function(result) {
    console.log('Success! Results:', result);
  })
  .catch(function(error) {
    console.error('Something went wrong!', error);
  });

Setelah menjalankan code di atas, callback server akan menampilkan informasi tentang  payment tersebut.

Source code script di atas bisa ambil dari sini ya..

https://github.com/akhdaniel/stellar

 

Akhmad D. Sembiring
Blockchain Expert Indonesia