initial commit: demo: shows contratcs, checks ids or contracts.

This commit is contained in:
Sergey Chernov 2025-04-15 00:23:21 +03:00
commit e089e5989c
22 changed files with 2110 additions and 0 deletions

1246
.gigaide/gigaide.properties Normal file

File diff suppressed because it is too large Load Diff

48
.gitignore vendored Normal file
View File

@ -0,0 +1,48 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Kotlin ###
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
/test_contracts/
.idea

3
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

7
.idea/codeStyles/Project.xml generated Normal file
View File

@ -0,0 +1,7 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<ScalaCodeStyleSettings>
<option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
</ScalaCodeStyleSettings>
</code_scheme>
</component>

5
.idea/codeStyles/codeStyleConfig.xml generated Normal file
View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

17
.idea/gradle.xml generated Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

6
.idea/kotlinc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="2.0.10" />
</component>
</project>

6
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17 (2)" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

62
REAMDE.md Normal file
View File

@ -0,0 +1,62 @@
# INDIGO DEMO command line tool
This demo shows how to connect to the private Universa network, check the contract ID for network approval,
load binary contract file, show some of its information and check its network status.
## Some details
File [indigo_demo_2025.json](src/main/resources/topologies/indigo_demo_2025.json)
contains actual private network configuration.
[Main.kt](src/main/kotlin/Main.kt) is a simple CLI tool that does it all.
Source [Uni.kt](src/main/kotlin/Uni.kt) contains a simple connection pool for universa
clients to run in parallel with coroutines.
## Contract IDs and Files
When using INDIGO demo, see [History](https://indigo.8-rays.dev/operations). In the
operations history you can see contracts binary and in text form (some key fields for the demo).
You can also copy the contract ID (click on it in the `contract` line) or download its binary.
Both can be used with this tool to show and check network status.
## Important note on contract approval states
Contracts, taken from the INDIGO, are not necessarily approved. For example, when you transfer funds, or pay invoices, some of the coin contracts will be modified, so old versions, presented in the logs, will not be approved anymore. This is quite normal and is a core feature of the Universa network.
## Usage sample
If you have binary distribution built with gradle task `./gradlew installDist`, you can
run it from a console. Alternatively, you can download, unpack and run the same the prebuilt demo: [indigo_demo_sample.zip](prebuilt_demo/indigo_demo_sample.zip).
```
build/install/indigo_demo_sample/bin/indigo_demo_sample -c test_contracts/indigo_2025-04-14T20-22-45.962Z.unicon
INDIGO sample console tool
Connecting to Universa network...
Connected. Here is the list of nodes:
http://31.41.155.11:8080 or https://31.41.155.11: J4ePqUDVy9Tj2n5pV9UCMxR1qhxS7eHMbUNzRXA6SEcwRF6kSNf5j1mDV9gbVnrk41Lwy2FY
http://37.9.5.102:8080 or https://37.9.5.102: JCi984dnqdgGq3YkYgLqbQKciMRqVhaE5hLSBi8vcfsNKw2KTR63ATCSfokBZ46wLT13PYag
http://37.9.4.133:8080 or https://37.9.4.133: J2ryG4uxnZxDUUoE8fz1ioPsdWcbwMkUMcZju6ZTpSTFJjF11Kd1Wn23DRrREbgxRNjq13BK
http://37.9.4.137:8080 or https://37.9.4.137: JfcHBZ4Wicj4t9YuTZDsKXsGGWstTgpftt7fnrWiro2hchNy2F9sHLT4x6RWDs8Hrh5EZyAq
Loaded contract: A0tD/Zc3QZ/hxfAESHb4C+Mzsd6VWRqVh4SMouplq7WfH9qUaaDZwgFS4DdVglhu4ks2raGPWYcgfsPfkxyg4i3sm9wiDIiR/VnwQ8v6GqeVVED6TOp8kSERpJFyCYRK
Definition ----------------------------------------------
Created : 2025-04-05T02:24:48+03:00[Europe/Moscow]
Expires : 2030-04-05T02:24:48+03:00[Europe/Moscow]
Ext.type : null
Definition: {short_currency=TINDIGO, name=IndigoTest, description=Indigo test token, currency=TINDIGO}
State ---------------------------------------------------
Revision : 1
Branch : null/0
State data : {amount=5.0E+2}
Transactional -------------------------------------------
data: {}
Checking contract Id: A0tD/Zc3…: Rejected
```
See above for the actual contracts.

44
build.gradle.kts Normal file
View File

@ -0,0 +1,44 @@
plugins {
kotlin("jvm") version "2.0.10"
application
}
group = "net.sergeych"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
maven("https://maven.universablockchain.com")
}
application {
mainClass.set("net.sergeych.MainKt")
}
dependencies {
implementation("com.icodici:universa_core:3.14.7")
implementation("net.sergeych:unikrypto:1.2.5-SNAPSHOT")
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(17)
}
tasks.register<Jar>("fatJar") {
archiveBaseName.set("my-console-app") // Change to your desired JAR name
manifest {
attributes["Main-Class"] = application.mainClass.get() // Set the main class
}
from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }) // Include dependencies
with(tasks.jar.get() as CopySpec) // Include the default jar contents
}
tasks.build {
dependsOn(tasks.named("fatJar")) // Ensure fatJar is built with the build task
}

1
gradle.properties Normal file
View File

@ -0,0 +1 @@
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Sun Apr 13 16:13:31 MSK 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Executable file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

Binary file not shown.

5
settings.gradle.kts Normal file
View File

@ -0,0 +1,5 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "indigo_demo_sample"

85
src/main/kotlin/Main.kt Normal file
View File

@ -0,0 +1,85 @@
package net.sergeych
import com.icodici.universa.HashId
import com.icodici.universa.contract.TransactionPack
import kotlinx.coroutines.runBlocking
import net.sergeych.uni.Uni
import java.io.File
fun main(_args: Array<String>) {
val args = _args.toMutableList()
println("\nINDIGO sample console tool\n")
// val args = mutableListOf("-c", "???")
runBlocking {
println("Connecting to Universa network...")
// connect to the network and print out nodes info
Uni.versa {
println("Connected. Here is the list of nodes:")
topologyInfo.forEach {
println("${it.ipUrl} or ${it.domainUrl}: ${it.keyAddress}")
}
}
while (args.isNotEmpty()) {
if (args[0] == "-h") {
println("\nUsage:")
println(" -c <contractID | contractFile> - check contract approval")
println(" -h - this help")
break
}
processCheckContract(args)
}
// universa client runs background coroutines here, so we shall cancel them
System.exit(0)
}
}
/**
* if args start with "-c", checks the contractId or loads the contract using args[1]
* and checks network approval, and remove both arguments from args array.
*/
suspend fun processCheckContract(args: MutableList<String>) {
if (args[0] == "-c") {
val contractId = if (args[1].endsWith(".unicon")) {
// got a file, load it using TransactionPack format (common for contracts):
val c = TransactionPack.unpack(
File(args[1]).readBytes()
)
// and extract its main contract:
.contract
println("\nLoaded contract: ${c.id.toBase64String()}")
println("Definition ---------------------------------------------- ")
println("Created : ${c.definition.createdAt}")
println("Expires : ${c.definition.expiresAt}")
println("Ext.type : ${c.definition.extendedType}")
println("Definition: ${c.definition.data}")
println("State --------------------------------------------------- ")
println("Revision : ${c.state.revision}")
println("Branch : ${c.state.branchId}/${c.state.branchRevision}")
println("State data : ${c.state.data}")
if( c.transactional != null ) {
println("Transactional -------------------------------------------")
println("data: ${c.transactional!!.data}")
}
// return its id for further checks:
c.id
} else
HashId.withDigest(args[1])
// -c <contract-id | contract-file>
// remove arguments
args.removeAt(0)
args.removeAt(0)
// check contract approval from the universa network:
print("\nChecking contract Id: $contractId: ")
val isApproved = Uni.versa { isApprovedByNetwork(contractId) }
println(if (isApproved) "Approved" else "Rejected")
}
}

191
src/main/kotlin/Uni.kt Normal file
View File

@ -0,0 +1,191 @@
package net.sergeych.uni
import com.icodici.crypto.PrivateKey
import com.icodici.crypto.PublicKey
import com.icodici.universa.ErrorRecord
import com.icodici.universa.HashId
import com.icodici.universa.node.ItemState
import com.icodici.universa.node2.network.Client
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import net.sergeych.mp_logger.LogTag
import net.sergeych.mp_logger.exception
import net.sergeych.mp_logger.info
import net.sergeych.mp_logger.warning
import net.sergeych.mp_tools.decodeBase64
import java.io.File
/**
* This is a rather simple connection pool for the threaded Universa clients
* to use with Kotlin coroutines.
*
* Uni pool is needed as Universa's client is blocking old-school Java code, and to
* use it with coroutines th pool is needed.
*
* Note that you can use Universa JAVA API directly. Also, indigo project uses multiplatform
* library that works now on JS and JVM the same way. It will be made public on release.
*/
object Uni : LogTag("UNI") {
// How many worker clients to use
val Parallelism = 2
// name of the topology file in resources/topologies, see source tree.
// it must not differ too much from the network (small changes are ok)
val NetworkName = "indigo_demo_2025"
/**
* The client's private key. We use "white" key that allows to execute paid operations
* for free. This is usual for private networks.
*/
private val key = PrivateKey(
File("./white.private.unikey")
.readBytes()
)
/**
* The number of allocated clients
*/
var allocated = 0
private set
// clients pool
private val pool = Channel<Context>(Parallelism)
// mutex to guard pool access
private val access = Mutex()
/**
* Get a client from the pool or allocate a new one, and execute [f] in it's
* context.
*/
suspend fun <T> versa(f: suspend Context.() -> T): T {
val x = access.withLock {
pool.tryReceive().getOrNull()
?: run {
if (allocated < Parallelism) {
info { "Allocating new client, currenly there are $allocated" }
Context.connect(NetworkName, key).also { allocated++ }.also {
info { "Allocated new client, currenly there are $allocated" }
}
} else null
}
} ?: pool.receive()
return try {
x.f().also {
access.withLock { pool.send(x) }
}
} catch (t: IllegalStateException) {
warning { "Critical exception, will re-connect the client: $t" }
allocated--
throw t
} catch (t: Throwable) {
exception { "unexpected in UNI to t" to t }
access.withLock { pool.send(x) }
throw t
}
}
/**
* Kotlin wrapper for the Universa's java based registration result.
*/
sealed class URegistrationResult {
/**
* true if the registration is approved by the network
*/
@Suppress("unused")
val approved by lazy {
this is Approved
}
/**
* Approved state, with extended [state] information
*/
data class Approved(val state: ItemState) : URegistrationResult() {
override fun toString(): String {
return state.toString()
}
}
/**
* Rejected state, with extended [state] information and list of [errors]
* as reported by the network node.
*/
class Rejected(
val errors: List<ErrorRecord>,
val state: ItemState,
) : URegistrationResult() {
override fun toString(): String {
return "$state: ${errors.joinToString(", ")}"
}
}
}
/**
* Context is a wrapper for the Universa's java based client to be used
* with [Uni] pool and Kotlin coroutines.
*/
class Context(private val c: Client) {
data class TopologyInfo(
val nodeNumber: Int,
val ipUrl: String,
val domainUrl: String,
val keyAddress: String,
)
/**
* Current network topology (configuration): urls, node numbers,
* public keys, etc.
*/
val topologyInfo by lazy {
c.topology.map {
TopologyInfo(
it.getIntOrThrow("number"),
it.getArray("direct_urls").first() as String,
it.getArray("domain_urls").first() as String,
PublicKey(it.getStringOrThrow("key").decodeBase64()).longAddress.toString()
)
}
}
/**
* Register a Universa TransactionPack with one or more contracts.
* It polls the network until the consensus will be reached.
*/
@Suppress("unused")
fun register(packed: ByteArray): URegistrationResult {
while (true) {
val ir = c.register(packed, 30_000)
val state = ir.state
if (state.isPending) continue
if (state.isApproved) return URegistrationResult.Approved(state)
else return URegistrationResult.Rejected(ir.errors, state)
}
}
/**
* Check that qualified majority of the network has approved the contract
* with [contractId]
* @param threshold is a percentage of the network size, default is 40%
* @return true if the contract is approved by the network
*/
fun isApprovedByNetwork(contractId: HashId, threshold: Double = 0.4): Boolean {
return c.isApprovedByNetwork(contractId, threshold, 15_000)
}
companion object {
/**
* Create a new client and connect to the network. This is not used directly
* mostly, but is used by [Uni] pool.
*/
fun connect(networkName: String, key: PrivateKey): Context {
val c = Client(networkName, null, key)
return Context(c)
}
}
}
}

View File

@ -0,0 +1,49 @@
{
"list": [
{
"number": 1,
"domain_urls": [
"https://31.41.155.11"
],
"name": "node-01",
"direct_urls": [
"http://31.41.155.11:8080"
],
"key": "HggcAQABxAAB5IfycVepakIjOt3c5eyLFswYH8dokrmHTyRIgaCSz+EY+mm8hM2Cn1PJjyiJj4K1A8CPN9p9mj6z/yyGSH6pvW3HMGs6Az7KvhGbZJlsFP0tNy6A3YQEWP/XToSqtT3f0Ji/r2nYw2zEgnGvOBkkcyN/EEslnxTj1R3fZlaSHh9Uem6NFk62ZxSBj8hJkvfHbTB/XZ2z8wtpwcAJClylITbbCSg9RdXoD8ZwCJMaCWasxfdo5+sMYTcABYFErbw8ndeQ5aL3N2+XiFM8WO5wQnd3SNTYUQGucBkXO5zqmZjnreVOWIsQtKzjwH4WIi57kz+87V72TbDrX0jYMYsOSw=="
},
{
"number": 2,
"domain_urls": [
"https://37.9.5.102"
],
"name": "node-02",
"direct_urls": [
"http://37.9.5.102:8080"
],
"key": "HggcAQABxAAB3GST2bRm2SrwypfKZRplqDwLUvDF7DoRgVMZfzOHzYodHfIpNrRKZfJdr63UdpK6359G1TAAHm52UaLCaCqBZNuFDqE9s9fEe+2UoSzoMKGG0NtgFD2HdDhuNWw4LnqZiZ5lPlZuUKtxVCzhlI0SNweBKMn0oopjdOYfx7hkPHVB2TyADXPrcnxFHEpc6USjJgP3aHPgum4CxYD09KTF59t5W+B+rDpTd/ro3ENBSFi9xlt4qMrLx5KzIdm8IqcsEm+mTYS5mx0F4e6wlCiXElwGe1NdXNwb/A8S2JBSUKP2CfSKdJtB0D7GHFnMuF3+u29/pykBOvlUoUa4S5QxJQ=="
},
{
"number": 3,
"domain_urls": [
"https://37.9.4.133"
],
"name": "node-03",
"direct_urls": [
"http://37.9.4.133:8080"
],
"key": "HggcAQABxAABtTajk8wkzstB+mmj09fkP/a9IqX4tVuuXnd/fO6a3TAjNbulqtkvVyfhu2DeUdUFiYP9kc+YQmHsIe5T/xZgdecWAbHKT0Ok530nLju8dog+75j6aCqD+winCCb+s7dzAYNIsKS0QgBPPWyBUyDL+di17s2Z5U2mibV+sXQYfWU4Gy02WNuavC8QZ0gA7K3Ah6ohR/Yn37WpiWvS+kQOnZF/q/8LYRQgxdDrztzTgpouggwk/1VJ181fYcXq/54n+L5yV2M0GZy7B942ce07MV6EGmQJu4eoOQi8DN3Ee30WOuIIiEyiQLMJjva0uxvkXmlftsr8rGiLXB+kiMd2fQ=="
},
{
"number": 4,
"domain_urls": [
"https://37.9.4.137"
],
"name": "node-04",
"direct_urls": [
"http://37.9.4.137:8080"
],
"key": "HggcAQABxAABkGzNgQnnNh/aNR3zQujD/6mgcqqfZ3tl14DDLhXLunUhc8hkn3y+ViukIj1qbkPi6Ps5irDZ2TzVfepoVWqX+XkI8wUbXKpDN/zWYx9kW4/soA4C7KS6fS/NFsFflUyzDNQeQXmiQkPTNnn43sdSqYb6Zr3I7Wa6mEwIP7MakKo6SbJQ/gTdXPlKWnU1nGJISMowCfhawYQLZgI5URsgS3VV7Owb3Yo4IZ0YNDTceboY4ljYuc/R2LqJcGjcWfSweaHV2T64RY6yQt1W0h2KweK99cflJdh/QSCqBhRdSYYfgKDlmp2ZTvrrfj0bbz2mPBh5JG5RQe+O9MzT0Is4ew=="
}
],
"updated": 1742911675
}

BIN
white.private.unikey Normal file

Binary file not shown.