Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update PRG interface and implementation #6

Merged
merged 34 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
1a2ff37
create README
sisyphusSmiling Oct 3, 2023
ef58175
first pass as PRG implementation
sisyphusSmiling Oct 3, 2023
6347a40
add references
sisyphusSmiling Oct 4, 2023
411763d
update flow.json
sisyphusSmiling Oct 4, 2023
47d84a3
add open source docs
sisyphusSmiling Oct 4, 2023
dd7b295
fix CoinToss contract bugs + add supporting txns
sisyphusSmiling Oct 4, 2023
e4fcf22
add FlowToken transfer txn
sisyphusSmiling Oct 4, 2023
17a1416
Apply suggestions from code review
sisyphusSmiling Nov 6, 2023
30bbdc4
update bigEndianBytesToWord64() pre-condition & message
sisyphusSmiling Nov 6, 2023
19c1190
update instances of PRG.bytesToWord64() to .bigEndianBytesToWord64()
sisyphusSmiling Nov 6, 2023
f1d006f
remove PRG.sourceOfRandomness field - state storage not necessary
sisyphusSmiling Nov 6, 2023
3645694
update PRG.nextUInt64() final xor shift
sisyphusSmiling Nov 6, 2023
90ca8fe
rename PseudoRandomGenerator to XorShift128Plus & rename instances
sisyphusSmiling Nov 6, 2023
8e7f756
update prg.next_uint64() calling transactions distinguishing single v…
sisyphusSmiling Nov 6, 2023
d1dd0fc
rename PseudoRandomGenerator.cdc to XorShift128Plus.cdc
sisyphusSmiling Nov 6, 2023
7e44dda
remove RandomBeaconHistory transactions
sisyphusSmiling Nov 7, 2023
9e5e9c4
rename XorShift128Plus to Xorshift128plus & update instances
sisyphusSmiling Nov 7, 2023
ce51fcd
refactor Xorshift128plus.PRG from resource to struct & update its ins…
sisyphusSmiling Nov 7, 2023
d980bae
add getter script for array of random UInt64 from prg
sisyphusSmiling Nov 7, 2023
8a392d0
simplify next_uint64 script & add comment
sisyphusSmiling Nov 7, 2023
e05641a
clarify script comments
sisyphusSmiling Nov 7, 2023
850cca7
fix iterative_next_uint64 txn and clarify comments
sisyphusSmiling Nov 7, 2023
d9eecda
fix PRG instantiation in CoinToss to match new interface
sisyphusSmiling Nov 7, 2023
6e963b3
fix iterative_next_uint64 PRG instantiation
sisyphusSmiling Nov 7, 2023
5f5ea13
add clarifying comments to Xorshift128plus contract
sisyphusSmiling Nov 7, 2023
c439f1c
fix PRG instantiation in script to match new interface
sisyphusSmiling Nov 7, 2023
1f72ce7
update CONTRIBUTING to name random-coin-toss repo
sisyphusSmiling Nov 7, 2023
cbf5d3e
Apply suggestions from code review
sisyphusSmiling Nov 7, 2023
e9157d5
update Xorshift128plus contract with PR feedback
sisyphusSmiling Nov 7, 2023
61cc807
Rename XorShift128Plus.cdc to Xorshift128plus.cdc
sisyphusSmiling Nov 7, 2023
ccf6d0e
update Xorshift128plus comments & error messages
sisyphusSmiling Nov 7, 2023
2f578d6
add comments to CoinToss contract
sisyphusSmiling Nov 8, 2023
256c1b2
Update CoinToss.cdc
sisyphusSmiling Nov 8, 2023
bf00c4e
update README info dialog about WIP status
sisyphusSmiling Nov 8, 2023
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
76 changes: 76 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure if there is a Flow team address available

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. This was taken from an existing open source template, so I'm not sure if we have a dedicated flow team email address for this purpose.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I asked around but didn't get an answer so far

complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
91 changes: 91 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Contributing to the Non-Fungible Token Standard

The following is a set of guidelines for contributing to the Flow NFT standard. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be changed to say ramdom coin toss implementation instead of NFT standard?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ha you're right! Good catch


#### Table Of Contents

[How Can I Contribute?](#how-can-i-contribute)

- [Reporting Bugs](#reporting-bugs)
- [Suggesting Enhancements](#suggesting-enhancements)
- [Pull Requests](#pull-requests)

[Styleguides](#styleguides)

- [Git Commit Messages](#git-commit-messages)

[Additional Notes](#additional-notes)


## How Can I Contribute?

You are free to contribute however you want! You can submit a bug report in an issue, suggest an enhancment, or even just make a PR for us to review. We just ask that you are clear in your communication and documentation of all your work so we can understand how you are trying to help.

### Reporting Bugs

#### Before Submitting A Bug Report

- **Search existing issues** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one.

#### How Do I Submit A (Good) Bug Report?

Explain the problem and include additional details to help maintainers reproduce the problem:

- **Use a clear and descriptive title** for the issue to identify the problem.
- **Describe the exact steps which reproduce the problem** in as many details as possible. When listing steps, **don't just say what you did, but explain how you did it**.
- **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
- **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
- **Explain which behavior you expected to see instead and why.**
- **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.

Provide more context by answering these questions:

- **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens.

Include details about your configuration and environment:

- **What's the name and version of the OS you're using**?
- **What's the name and version of the flow-cli that you are using**?

### Suggesting Enhancements

#### Before Submitting An Enhancement Suggestion

- **Perform a cursory search** to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.

#### How Do I Submit A (Good) Enhancement Suggestion?

Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue and provide the following information:

- **Use a clear and descriptive title** for the issue to identify the suggestion.
- **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
- **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
- **Include screenshots and animated GIFs**. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.
- **Explain why this enhancement would be useful** to be included in the standard.

### Pull Requests

The process described here has several goals:

- Maintain code quality
- Fix problems that are important to users

Please follow the [styleguides](#styleguides) to have your contribution considered by the maintainers.
Reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted.

## Styleguides

Before contributing, make sure to examine the project to get familiar with the patterns and style already being used.

### Git Commit Messages

- Use the present tense ("Add feature" not "Added feature")
- Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
- Limit the first line to 72 characters or less
- Reference issues and pull requests liberally after the first line


### Additional Notes

Thank you for your interest in contributing to the Flow Token Standards!
24 changes: 24 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org>
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# [WIP] Random Coin Toss

> :warning: This repo is still a work in progress - the underlying RandomBeaconHistory is also still a work in progress
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the RandomBeaconHistory contract in this repo the same core-protocol one? If yes I guess it is not WIP right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, the contract is finalized. I'll update this section


## Overview
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clear and easy-to-read doc 👌🏼


The contracts contained in this repo demonstrate how to use Flow's onchain randomness safely - safe randomness here
meaning non-revertible randomness.

Random sources are committed to the [`RandomBeaconHistory` contract](./contracts/RandomBeaconHistory.cdc) by the service
account at the end of every block. These random sources are catalogued chronologically, extending historically for every
associated block height to the initial commitment height.

Used on their own, these random sources are not safe. In other words, using the random source in your contract without
the framing of a commit-reveal mechanism would enable callers to condition their interactions with your contract on the
sisyphusSmiling marked this conversation as resolved.
Show resolved Hide resolved
random result. In the context of a random coin toss, I could revert my transaction if I didn't win - not a very fair
game.

To achieve non-revertible randomness, the contract should be structured to resolve in two phases:

1. Commit - Caller commits to the resolution of their bet with some yet unknown source of randomness (i.e. in the
future)
2. Reveal - Caller can then reveal the result of their bet

Though a caller could still condition the revealing transaction on the coin flip result, they've already incurred the
cost of their bet and would gain nothing by doing so.

## References

- [Secure Random Number Generator Forum Post](https://forum.onflow.org/t/secure-random-number-generator-for-flow-s-smart-contracts/5110)
- [RandomBeaconHistory PR - flow-core-contracts](https://github.com/onflow/flow-core-contracts/pull/375)
- [FLIP: On-Chain randomness history for commit-reveal schemes](https://github.com/onflow/flips/pull/123)
11 changes: 11 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Responsible Disclosure Policy

Flow was built from the ground up with security in mind. Our code, infrastructure, and development methodology helps us keep our users safe.

We really appreciate the community's help. Responsible disclosure of vulnerabilities helps to maintain the security and privacy of everyone.

If you care about making a difference, please follow the guidelines below.

# **Guidelines For Responsible Disclosure**

We ask that all researchers adhere to these guidelines [here](https://docs.onflow.org/bounties/responsible-disclosure/)
39 changes: 27 additions & 12 deletions contracts/CoinToss.cdc
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import "FungibleToken"
import "FlowToken"

import "RandomBeaconHistory"
import "PseudoRandomGenerator"

access(all) contract CoinToss {

access(self) let reserve: @FlowToken.Vault

access(self) let ReceiptStoragePath: StoragePath
access(all) let ReceiptStoragePath: StoragePath

access(all) event CoinTossBet(betAmount: UFix64, commitBlock: UInt64, receiptID: UInt64)
access(all) event CoinTossReveal(betAmount: UFix64, winningAmount: UFix64, commitBlock: UInt64, receiptID: UInt64)

access(all) resource Receipt {
access(all) let betAmount: UFix64
Expand All @@ -21,32 +26,42 @@ access(all) contract CoinToss {
// PRG implementation is not provided by the FLIP, we assume this contract
// imports a suitable PRG implementation

access(all) fun commitCointoss(bet: @FlowToken.Vault): @Receipt {
access(all) fun commitCoinToss(bet: @FungibleToken.Vault): @Receipt {
let receipt <- create Receipt(
betAmount: bet.balance
)
// commit the bet
// `self.reserve` is a `@FlowToken.Vault` field defined on the app contract
// `self.reserve` is a `@FungibleToken.Vault` field defined on the app contract
// and represents a pool of funds
self.reserve.deposit(from: <-bet)

emit CoinTossBet(betAmount: receipt.betAmount, commitBlock: receipt.commitBlock, receiptID: receipt.uuid)

return <- receipt
}

access(all) fun revealCointoss(receipt: @Receipt): @FlowToken.Vault {
let currentBlock = getCurrentBlock().height
if receipt.commitBlock >= currentBlock {
panic("cannot reveal yet")
access(all) fun revealCoinToss(receipt: @Receipt): @FungibleToken.Vault {
pre {
receipt.commitBlock <= getCurrentBlock().height: "Cannot reveal before commit block"
}

let winnings = receipt.betAmount * 2.0
let betAmount = receipt.betAmount
let commitBlock = receipt.commitBlock
let receiptID = receipt.uuid
let coin = self.randomCoin(atBlockHeight: receipt.commitBlock, salt: receipt.uuid)

destroy receipt

if coin == 1 {
return <- (FlowToken.createEmptyVault() as! @FlowToken.Vault)
emit CoinTossReveal(betAmount: betAmount, winningAmount: 0.0, commitBlock: commitBlock, receiptID: receiptID)
return <- FlowToken.createEmptyVault()
}

return <- (self.reserve.withdraw(amount: winnings) as! @FlowToken.Vault)

let reward <- self.reserve.withdraw(amount: betAmount * 2.0)

emit CoinTossReveal(betAmount: betAmount, winningAmount: reward.balance, commitBlock: commitBlock, receiptID: receiptID)

return <- reward
}

access(all) fun randomCoin(atBlockHeight: UInt64, salt: UInt64): UInt8 {
Expand All @@ -73,7 +88,7 @@ access(all) contract CoinToss {
self.reserve <- (FlowToken.createEmptyVault() as! @FlowToken.Vault)
let seedVault = self.account.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault)!
self.reserve.deposit(
from: <-seedVault.withdraw(amount: 100.0)
from: <-seedVault.withdraw(amount: 1000.0)
)

self.ReceiptStoragePath = /storage/CoinTossReceipt
Expand Down
Loading