• Stars
    star
    201
  • Rank 194,455 (Top 4 %)
  • Language
    Scala
  • License
    Creative Commons ...
  • Created almost 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Cryptographic primitives for Scala

Scrypto Build Status

Scrypto is an open source cryptographic toolkit designed to make it easier and safer for developers to use cryptography in their applications.

It was extracted from Scorex, open-source modular blockchain & cryptocurrency framework.

Public Domain.

If you want to check benchmarks for authenticated AVL+ trees, please visit dedicated repository. Use the repository as code examples for the trees also, though one code example is provided in "Authenticated Data Structures" section below.

Get Scrypto

Scrypto is available on Sonatype for Scala 2.12:

resolvers += "Sonatype Releases" at "https://oss.sonatype.org/content/repositories/releases/"

You can use Scrypto in your sbt project by simply adding the following dependency to your build file:

libraryDependencies += "org.scorexfoundation" %% "scrypto" % "2.2.0"

Hash functions

Supported hash algorithms are:

  • Blake2b
  • Keccak
  • Sha
  • Whirlpool
  • Skein
  • Stribog

Take a look at CryptographicHash interface and use supported hash algorithms like

Keccak512("some string or bytes")

All provided hash functions are secure, and their implementations are thread safe.

Commutative hash

You can create commutative hash from any hash function with CommutativeHash case class like CommutativeHash(Sha256). A hash function h is commutative if h(x,y)==h(y,x) , for all x and y.

Binary-to-text Encoding Schemes

Scrypto has implementations of few binary-to-text encoding schemes:

  • Base16
  • Base58
  • Base64

Example:

  val encoded = Base64.encode(data)
  val restored = Base64.decode(encoded)
  restored shouldBe data

Signing functions

Scrypto supports following elliptic curves:

  • Curve25519(& Ed25519)

Example:

  val curveImpl = new Curve25519
  val keyPair = curveImpl.createKeyPair()
  val sig = curveImpl.sign(keyPair._1, message)
  assert(curveImpl.verify(sig, message, keyPair._2))

Note on security: Scrypto provides a simple Scala wrapper for Curve25519-Java by Whisper Systems, so has the same security properties. JDK's SecureRandom is used to obtain seed bytes.

Authenticated data structures

Scrypto supports two-party authenticated AVL+ trees with the batching compression support and guaranteed verifier efficiency, as described in http://eprint.iacr.org/2016/994. The implementation can be found in the scorex.crypto.authds.avltree.batch package.

The overall approach is as follows. The prover has a data structure of (key, value) pairs and can perform operations on it using performOneOperation method. An operation (see scorex.crypto.authds.avltree.batch.Operation) is either a lookup or a modification. We provide sample modifications (such as insertions, removals, and additions/subtractions from the value of a given key), but users of this code may define their own (such as subtractions that allow negative values, unlike our subtractions). A modification may be defined to fail under certain conditions (e.g., a deletion of a key that is not there, or a subtraction that results in a negative value), in which case the tree is not modified. If the operation succeeds, it returns the value associated with the key before the operation was performed. The prover can compute the digest of the current state of the data structure via the digest method. At any point the prover may use generateProof, which will produce a proof covering the batch of operations (except the ones that failed) since the last generateProof.

The verifier is constructed from the digest that preceeded the latest batch of operations and the proof for the latest batch. The verifier can also be given optional parameters for the maximum number of operations (and at most how many of those are deletions) in order to guarantee a bound on the verifier running time in case of a malicious proof, thus mitigating denial of service attacks. Once constructed, the verifier can replay the same sequence of operations to compute the new digest and to be assured that the operations do not fail and their return values are correct. Note that the verifier is not assured that the sequence of operations is the same as the one the prover performed---it is assumed that the prover and verifier agree on the sequence of operations (two-party authenticated data structures are useful when the prover and verifier agree on the sequence of operations). However, if the verifier digest matches the prover digest after the sequence of operations, then the verifier is assured that the state of the data structure is the same, regardless of what sequence of operations led to this state.

We also provide unauthenticatedLookup for the prover, in order to allow the prover to look up values in the data structure without affecting the proof.

Here are code examples for generating proofs and checking them. In this example we demonstrate two batches of operations, starting with the empty tree. In the first batch, a prover inserts three values into the tree; in the second batch, the prover changes the first value, attempts to subtract too much from the second one, which fails, looks up the third value, and attempts to delete a nonexisting value, which also fails. We use 1-byte keys for simplicity; in a real deployment, keys would be longer.

  • First, we create a prover and get an initial digest from it (in a real application, this value is a public constant because anyone, including verifiers, can compute it by using the same two lines of code)
  import scorex.utils.Longs
  import scorex.crypto.authds.{ADKey, ADValue}
  import scorex.crypto.authds.avltree.batch._
  import scorex.crypto.hash.{Blake2b256, Digest32}

  val prover = new BatchAVLProver(keyLength = 1, valueLengthOpt = Some(8))
  val initialDigest = prover.digest
  • Second, we create the first batch of tree modifications, inserting keys 1, 2, and 3 with values 10, 20, and 30. We use com.google.common.primitives.Longs.toByteArray to get 8-byte values out of longs.
  val key1 = Array(1:Byte)
  val key2 = Array(2:Byte)
  val key3 = Array(3:Byte)
  val op1 = Insert(ADKey @@ key1, ADValue @@ Longs.toByteArray(10))
  val op2 = Insert(ADKey @@ key2, ADValue @@ Longs.toByteArray(20))
  val op3 = Insert(ADKey @@ key3, ADValue @@ Longs.toByteArray(30))
  • The prover applies the three modifications to the empty tree, obtains the first batch proof, and announces the next digest digest1.
  prover.performOneOperation(op1) // Returns Success(None)
  prover.performOneOperation(op2) // Returns Success(None)
  prover.performOneOperation(op3) // Returns Success(None)
  val proof1 = prover.generateProof()
  val digest1 = prover.digest
  • A proof is just an array of bytes, so you can immediately send it over a wire or save it to a disk.

  • Next, the prover attempts to perform five more modifications: changing the first value to 50, subtracting 40 from the second value (which will fail, because our UpDateLongBy operation is designed to fail on negative values), looking up the third value, deleting the key 5 (which will also fail, because key 5 does not exist), and deleting the third value. After the four operations, the prover obtains a second proof, and announces the new digest digest2

  val op4 = Update(ADKey @@ key1, ADValue @@ Longs.toByteArray(50))
  val op5 = UpdateLongBy(ADKey @@ key2, -40)
  val op6 = Lookup(ADKey @@ key3)
  val op7 = Remove(ADKey @@ Array(5:Byte))
  val op8 = Remove(ADKey @@ key3)
  prover.performOneOperation(op4) // Returns Success(Some(Longs.toByteArray(10)))
  // Here we can, for example, perform prover.unauthenticatedLookup(key1) to get 50
  // without affecting the proof or anything else
  prover.performOneOperation(op5) // Returns Failure
  prover.performOneOperation(op6) // Returns Success(Some(Longs.toByteArray(30)))
  prover.performOneOperation(op7) // Returns Failure
  prover.performOneOperation(op8) // Returns Success(Some(Longs.toByteArray(30)))
  val proof2 = prover.generateProof() // Proof only for op4 and op6
  val digest2 = prover.digest
  • We now verify the proofs. For each batch, we first construct a verifier using the digest that preceded the batch and the proof of the batch; we also supply an upper bound on the number of operations in the batch and an upper bound on how many of those operations are deletions. Note that the number of operations can be None, in which case there is no guaranteed running time bound; furthermore, the number of deletions can be None, in which case the guaranteed running time bound is not as small as it can be if a good upper bound on the number of deletion is supplied.

  • Once the verifier for a particular batch is constructed, we perform the same operations as the prover, one by one (but not the ones that failed for the prover). If verification fails at any point (at construction time or during an operation), the verifier digest will equal None from that point forward, and no further verifier operations will change the digest. Else, the verifier's new digest is the correct one for the tree as modified by the verifier. Furthermore, if the verifier performed the same modifications as the prover, then the verifier and prover digests will match.

  val verifier1 = new BatchAVLVerifier[Digest32, Blake2b256.type](initialDigest, proof1, keyLength = 1, valueLengthOpt = Some(8), maxNumOperations = Some(2), maxDeletes = Some(0))
  verifier1.performOneOperation(op1) // Returns Success(None)
  verifier1.performOneOperation(op2) // Returns Success(None)
  verifier1.performOneOperation(op3) // Returns Success(None)
  verifier1.digest match {
    case Some(d1) if d1.sameElements(digest1) =>
      //If digest1 from the prover is already trusted, then verification of the second batch can simply start here
      val verifier2 = new BatchAVLVerifier[Digest32, Blake2b256.type](d1, proof2, keyLength = 1, valueLengthOpt = Some(8), maxNumOperations = Some(3), maxDeletes = Some(1))
      verifier2.performOneOperation(op4) // Returns Success(Some(Longs.toByteArray(10)))
      verifier2.performOneOperation(op6) // Returns Success(Some(Longs.toByteArray(30)))
      verifier2.performOneOperation(op8) // Returns Success(Some(Longs.toByteArray(30)))
      verifier2.digest match {
        case Some(d2) if d2.sameElements(digest2) => println("first and second digest value and proofs are valid")
        case _ => println("second proof or announced digest NOT valid")
      }
    case _ =>
      println("first proof or announced digest NOT valid")
  }

Merkle Tree

[TODO: describe MerkleTree & MerkleProof classes]

Tests

Run sbt test from a folder containing the framework to launch tests.

Benchmarks

Run sbt bench:test from a folder containing the framework to launch embedded benchmarks.

License

The code is under Public Domain CC0 license means you can do anything with it. Full license text is in COPYING file

Contributing

Clone the repository

$git clone <repository> scrypto
$cd scrypto

The code uses Scalablytyped to generate Scala.js bindings for @noble/hashes. This video explains how the environment for ScalablyTyped is configured in this repository.

Before compiling the library with SBT, you need to install JS dependencies for ScalablyTyped. The configuration is in package.json.

$npm install
added 285 packages, and audited 286 packages in 20s
found 0 vulnerabilities

Then you can compile the library with SBT and run tests.

$sbt
sbt:scrypto> compile
sbt:scrypto> test

Your contributions are always welcome! Please submit a pull request or create an issue to add a new cryptographic primitives or better implementations.

More Repositories

1

cardano-sl

Cryptographic currency implementing Ouroboros PoS protocol
Haskell
3,757
star
2

cardano-node

The core component that is used to participate in a Cardano decentralised blockchain.
Haskell
2,934
star
3

plutus

The Plutus language implementation and tools
Haskell
1,472
star
4

plutus-pioneer-program

This repository hosts the lectures of the Plutus Pioneers Program. This program is a training course that the IOG Education Team provides to recruit and train software developers in Plutus, the native smart contract language for the Cardano ecosystem.
Haskell
1,389
star
5

daedalus

The open source cryptocurrency wallet for ada, built to grow with the community
TypeScript
1,230
star
6

essential-cardano

Repository for the Essential Cardano list
738
star
7

haskell.nix

Alternative Haskell Infrastructure for Nixpkgs
Nix
557
star
8

Scorex

Modular blockchain framework. Public domain
JavaScript
503
star
9

nami

Nami Wallet is a browser based wallet extension to interact with the Cardano blockchain. Support requests: https://iohk.zendesk.com/hc/en-us/requests/new
JavaScript
373
star
10

jormungandr

privacy voting blockchain node
Rust
366
star
11

plutus-apps

The Plutus application platform
Haskell
304
star
12

rust-byron-cardano

rust client libraries to deal with the current cardano mainnet (byron / cardano-sl)
Rust
276
star
13

hydra

Implementation of the Hydra Head protocol
Haskell
262
star
14

cardano-documentation

TypeScript
258
star
15

cardano-db-sync

A component that follows the Cardano chain and stores blocks and transactions in PostgreSQL
Haskell
254
star
16

ouroboros-network

An implementation of the Ouroboros family of consensus algorithms, with its networking support
Haskell
254
star
17

mantis

A Scala based client for Ethereum-like Blockchains.
Scala
227
star
18

cardano-ledger

The ledger implementation and specifications of the Cardano blockchain.
Haskell
223
star
19

cardano-js-sdk

JavaScript SDK for interacting with Cardano, providing various key management options, with support for popular hardware wallets
TypeScript
216
star
20

plutus-starter

A starter project for Plutus apps
Nix
198
star
21

lobster-challenge

Simple Plutus contract to help give Charles' stuffed lobster a name
Haskell
179
star
22

adrestia

APIs & SDK for interacting with Cardano.
Markdown
177
star
23

marlowe

Prototype implementation of domain-specific language for the design of smart-contracts over cryptocurrencies
Isabelle
174
star
24

bitte

Nix Ops for Terraform, Consul, Vault, Nomad
Nix
156
star
25

symphony-2

Immersive 3D Blockchain Explorer
JavaScript
127
star
26

mithril

Stake-based threshold multi-signatures protocol
Rust
126
star
27

cardano-addresses

Addresses and mnemonic manipulation & derivations
Haskell
125
star
28

iohk-ops

NixOps deployment configuration for IOHK devops
Nix
119
star
29

Alonzo-testnet

repository for the Alonzo testnet
Haskell
112
star
30

cardano-tutorials

ARCHIVED-This content in this repository is now located at https://docs.cardano.org/projects/cardano-node/
Makefile
112
star
31

stack2nix

Generate nix expressions for Haskell projects
Nix
99
star
32

iodb

Multiversioned key-value database, especially useful for blockchain
Scala
96
star
33

nix-tools

Translate Cabals Generic Package Description to a Nix expression
95
star
34

marlowe-cardano

Marlowe smart contract language Cardano implementation
Haskell
90
star
35

cardano-byron-cli

Cardano Command Line Interface (CLI) (Deprecated)
Rust
84
star
36

cardano-base

Code used throughout the Cardano eco-system
Haskell
83
star
37

react-polymorph

React components with highly customizable logic, markup and styles.
JavaScript
79
star
38

high-assurance-legacy

Legacy code connected to the high-assurance implementation of the Ouroboros protocol family
Haskell
78
star
39

shelley-testnet

Support triage for the Shelley testnet
70
star
40

cardano-crypto

This repository provides cryptographic libraries that are used in the Byron era of the Cardano node
C
67
star
41

plutus-use-cases

Plutus Use Cases
66
star
42

cardano-ops

NixOps deployment configuration for IOHK/Cardano devops
Nix
65
star
43

iohk-nix

nix scripts shared across projects
Nix
62
star
44

cardano-rt-view

RTView: real-time watching for Cardano nodes (ARCHIVED)
Haskell
59
star
45

spongix

Proxy for Nix Caching
Go
59
star
46

nix-hs-hello-windows

Cross compiling Hello World (haskell) to Windows using nix.
Nix
58
star
47

symphony

Symphony v1
JavaScript
53
star
48

cardano-ledger-byron

A re-implementation of the Cardano ledger layer, replacing the Byron release
Haskell
52
star
49

rscoin-haskell

Haskell implementation of RSCoin
Haskell
51
star
50

cardano-node-tests

System and end-to-end (E2E) tests for cardano-node.
Python
51
star
51

project-icarus

Icarus, a reference implementation for a lightweight wallet developed by the IOHK Engineering Team.
45
star
52

cardano-rest

HTTP interfaces for interacting with the Cardano blockchain.
Haskell
44
star
53

foliage

🌿 Foliage is a tool to create custom Haskell package repositories, in a fully reproducible way.
Haskell
42
star
54

offchain-metadata-tools

Tools for creating, submitting, and managing off-chain metadata such as multi-asset token metadata
Haskell
42
star
55

cicero

event-driven automation for Nomad
Go
41
star
56

medusa

3D github repository visualiser
JavaScript
41
star
57

nothunks

Haskell
39
star
58

partner-chains

Substrate node with capability of communicating with Cardano network
Rust
38
star
59

bech32

Haskell implementation of the Bech32 address format (BIP 0173).
Haskell
37
star
60

catalyst-core

⚙️ Core Catalyst Governance Engine and utilities.
Rust
37
star
61

smash

Stakepool Metadata Aggregation Server
Haskell
36
star
62

chain-libs

blockchain libs
Rust
35
star
63

cardanodocs.com-archived

Cardano Settlement Layer Documentation
HTML
35
star
64

devx

The Developer Experience Shell - This repo contains a nix develop shell for haskell. Its primary purpose is to help get a development shell for haskell quickly and across multiple operating systems (and architectures).
Nix
35
star
65

io-sim

Haskell's IO simulator which closely follows core packages (base, async, stm).
Haskell
35
star
66

iohk-monitoring-framework

This framework provides logging, benchmarking and monitoring.
Haskell
33
star
67

mallet

JavaScript
32
star
68

project-icarus-chrome

Icarus, a reference implementation for a lightweight wallet developed by the IOHK Engineering Team.
JavaScript
32
star
69

js-cardano-wasm

various cardano javascript using wasm bindings
Rust
31
star
70

cardano-shell

Node shell, a thin layer for running the node and it's modules.
Haskell
31
star
71

cardano-launcher

Shelley cardano-node and cardano-wallet launcher for NodeJS applications
TypeScript
31
star
72

cardano-world

Cardano world provides preprod and preview cardano networks, configuration documentation and miscellaneous automation.
Nix
30
star
73

rscoin-core

Haskell
29
star
74

quickcheck-dynamic

A library for stateful property-based testing
Haskell
27
star
75

stakepool-management-tools

JavaScript
27
star
76

cardano-haskell-packages

Metadata for Cardano's Haskell package repository
Shell
24
star
77

cardano-haskell

Top level repository for building the Cardano Haskell node and related components and dependencies.
Shell
24
star
78

cardano-configurations

A common place for finding / maintaining configurations of various services of the Cardano eco-system
24
star
79

Developer-Experience-working-group

23
star
80

cardano-transactions

Library utilities for constructing and signing Cardano transactions.
Haskell
23
star
81

psg-cardano-wallet-api

Scala client to the Cardano wallet REST API
Scala
22
star
82

marlowe-ts-sdk

Marlowe TypeScript SDK
TypeScript
22
star
83

sanchonet

Sources for the SanchoNet website
TypeScript
21
star
84

pvss-haskell

Haskell
21
star
85

cardano-wallet-legacy

Official Wallet Backend & API for Cardano-SL
Haskell
21
star
86

scalanet

Scala
20
star
87

cardano-explorer

Backend solution powering the cardano-explorer. ⚠️ See disclaimer below. ⚠️
Haskell
20
star
88

formal-ledger-specifications

Formal specifications of the cardano ledger
Agda
19
star
89

metadata-registry-testnet

Nix
19
star
90

casino

Demo / PoC / implementation of IOHK MPC protocols
Haskell
19
star
91

hackage.nix

Automatically generated Nix expressions for Hackage
19
star
92

cardano-clusterlib-py

Python wrapper for cardano-cli for working with cardano cluster
Python
19
star
93

catalyst-voices

🎙️ Catalyst Voices provides a unified experience and platform including production-ready liquid democracy, meaningful collaboration opportunities & data-driven context for better onboarding & decisions.
Dart
19
star
94

marlowe-starter-kit

This repository contains lessons for using Marlowe via REST and at the command line. It is meant to be used with demeter.run or with a Docker deployment of Marlowe Runtime.
Jupyter Notebook
19
star
95

js-chain-libs

chain-libs javascript SDK
Rust
18
star
96

cardano-coin-selection

A library of algorithms for coin selection and fee balancing.
Haskell
18
star
97

ouroboros-consensus

Implementation of a Consensus Layer for the Ouroboros family of protocols
Haskell
18
star
98

marlowe-pioneer-program

Lectures, documentation, and examples for Marlowe Pioneer Program.
Haskell
18
star
99

chain-wallet-libs

Rust
18
star
100

jortestkit

jormungandr QA
Rust
17
star