Skip to content

AergoLite﹢Go

Bernardo Ramos edited this page Feb 17, 2022 · 2 revisions

For Ruby we use the go-sqlite3 wrapper

First install AergoLite on your computer.

Then install the wrapper with this line:

go get github.com/aergoio/go-aergolite

Note: The wrapper uses the already installed SQLite library containing AergoLite. So it must be present on the device.

Example Code

package main

import (
  "database/sql"
  sqlite "github.com/aergoio/go-aergolite"
  "github.com/buger/jsonparser"
  "time"
  "strconv"
)

func main() {

  sql.Register("sqlite3_custom", &sqlite.SQLiteDriver{
    ConnectHook: func(conn *sqlite.SQLiteConn) error {
      if err := conn.RegisterFunc("on_sign_transaction", on_sign_transaction, true); err != nil {
        return err
      }
      if err := conn.RegisterFunc("transaction_notification", on_transaction, true); err != nil {
        return err
      }
      if err := conn.RegisterFunc("update_notification", on_update, true); err != nil {
        return err
      }
      return nil
    },
  })

  // open the database
  db, err := sql.Open("sqlite3_custom", "file:test.db?blockchain=on&discovery=local:4329&password=test")
  if err != nil {
    println("failed to open the database: " + err.Error())
    return
  }

  // check if the db is ready
  for {
    rows, err := db.Query("PRAGMA blockchain_status")
    if err != nil {
      println("failed to get sync_status: " + err.Error())
      return
    }
    rows.Next()
    var result string
    err = rows.Scan(&result)
    if err != nil {
      println("failed to scan the result: " + err.Error())
      return
    }
    rows.Close()
    println(result)
    isReady, _ := jsonparser.GetBoolean([]byte(result), "db_is_ready")
    if isReady {
      break
    }
    time.Sleep(1000 * time.Millisecond)
  }

  // now we can access the db
  println("OK, ready!")

}

// Signing a transaction from the blockchain admin
func on_sign_transaction(data string) string {
  //signature = sign(data, privkey)
  //return hex.EncodeToString(pubkey) + ":" + hex.EncodeToString(signature)
  return ""
}

// Receiving a notification of a processed transaction
func on_transaction(nonce uint64, status string) {
  println("transaction " + strconv.FormatUint(nonce,10) + ": " + status)
}

// Receiving notification of local db update
func on_update() {
  println("event: the db was updated")
}
Clone this wiki locally