diff --git a/.dprint.json b/.dprint.json new file mode 100644 index 0000000..d98f016 --- /dev/null +++ b/.dprint.json @@ -0,0 +1,29 @@ +{ + "typescript": { + }, + "json": { + }, + "markdown": { + "ignoreDirective": "prettier-ignore", + "ignoreFileDirective": "prettier-ignore-file", + "ignoreStartDirective": "prettier-ignore-start", + "ignoreEndDirective": "prettier-ignore-end" + }, + "toml": { + }, + "excludes": [ + "**/html*", + "**/.yarn", + "**/node_modules", + "tools/**/*min.js", + "tools/plugin/chart", + "tools/plugin/mermaid.js", + "**/*-lock.json" + ], + "plugins": [ + "https://plugins.dprint.dev/typescript-0.87.1.wasm", + "https://plugins.dprint.dev/json-0.17.4.wasm", + "https://plugins.dprint.dev/markdown-0.16.0.wasm", + "https://plugins.dprint.dev/toml-0.5.4.wasm" + ] +} diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..1146baf --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,32 @@ +name: Checks +on: + workflow_dispatch: # Allows you to run this workflow manually from the Actions tab + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + ci-checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Cache + id: cache + uses: actions/cache@v3 + with: + path: ~/.cache/dprint # TODO add more paths here for various checkers + key: ${{ runner.os }}-${{ hashFiles('**/*dprint.json') }} + + - name: Format Check (dprint) + uses: dprint/check@v2.2 + with: + config-path: .dprint.json + + # FIXME .mlc.toml config not working... https://github.com/becheran/mlc/issues/78 + - name: Markup Link Checker (mlc) + uses: becheran/mlc@v0.16.2 + with: + args: "./content/ --ignore-links '*slides.md,*slides.html,*twitter.com*,*sec.gov*,*support.giphy.com*,*bitdefender.com*,*etherscan.io*,*cryptoslate.com*,*golden.com*,'" diff --git a/.github/workflows/link-check.yml b/.github/workflows/link-check.yml deleted file mode 100644 index ae149a7..0000000 --- a/.github/workflows/link-check.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Check Links - -on: - push: - branches: - - FIXME # need to SKIP any symbolic links! As internal links within them are likely broken! - -jobs: - markdown-link-check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: gaurav-nelson/github-action-markdown-link-check@v1 - with: - # links that are okay (http status returns 200) will not be shown - use-quiet-mode: 'yes' - # showing the details on links returning error - use-verbose-mode: 'yes' - # Custom config just ignores crates.io links because they are always false positive - config-file: '.github/workflows/mlc_config.json' diff --git a/.github/workflows/mlc_config.json b/.github/workflows/mlc_config.json deleted file mode 100644 index 7b5955f..0000000 --- a/.github/workflows/mlc_config.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "ignorePatterns": [ - { - "pattern": "^./*/", - "pattern": "\\slides.html", - "pattern": "^https://crates.io", - "pattern": "^https://github.com/Polkadot-Blockchain-Academy" - } - ] -} diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 02b8a59..03a8d49 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,13 +1,11 @@ # From https://github.com/rust-lang/mdBook/wiki/Automated-Deployment%3A-GitHub-Actions#raw-example name: Build and push to `html-*` branches, publish to Pages on: + workflow_dispatch: # Allows you to run this workflow manually from the Actions tab push: branches: - main - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages permissions: contents: write # needed to push to branches @@ -77,7 +75,6 @@ jobs: with: path: ./html-book - # Deployment job deploy: environment: name: github-pages diff --git a/.gitignore b/.gitignore index 8f83dcd..d5cc887 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,17 @@ -# Rust artifacts -**/target - # Build artifacts /html* -# Jupyter artifacts +# Rust artifacts +**/target +# Jupyter artifacts **/.ipynb_checkpoints/** # Some common ones tmp +tmp/** +*.log +log/** .vscode .idea/ *.iml @@ -18,8 +20,6 @@ tmp out/ .DS_Store .svn -log/*.log -tmp/** node_modules/ .sass-cache _static/ diff --git a/.mlc.toml b/.mlc.toml new file mode 100644 index 0000000..5e928b1 --- /dev/null +++ b/.mlc.toml @@ -0,0 +1,20 @@ +# FIXME this config is not working... https://github.com/becheran/mlc/issues/78 +# Print debug information to console +debug = false +# Do not check web links +offline = false +# Check the exact file extension when searching for a file +match-file-extension = true +# List of files and directories which will be ignored +ignore-path = [""] +# List of links which will be ignored +ignore-links = [ + "*slides.md,*slides.html,*twitter.com*,*sec.gov*,*support.giphy.com*,*bitdefender.com*,*etherscan.io*,*cryptoslate.com*,*golden.com*,", +] +# List of markup types which shall be checked +markup-types = ["Markdown", "Html"] +# Wait time in milliseconds between http request to the same host +# Consider use only if getting `429 - Too Many Requests` +throttle = 0 +# Path to the root folder used to resolve all relative paths +root-dir = "./content/" diff --git a/.prettierrc.js b/.prettierrc.js index d574bcf..9561c2d 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,12 +1,12 @@ module.exports = { - arrowParens: 'avoid', - endOfLine: 'lf', + arrowParens: "avoid", + endOfLine: "lf", semi: true, singleQuote: true, - trailingComma: 'es5', + trailingComma: "es5", overrides: [ { - files: '*.md', + files: "*.md", options: { singleQuote: false, }, diff --git a/Makefile.toml b/Makefile.toml index 63009ab..ebef83c 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -27,16 +27,25 @@ skip_crate_env_info = true category = "Install" alias = "install" - [tasks.install] description = "Install dependencies for slides and book tooling." category = "Install" -dependencies = ["install-slides", "install-book"] +dependencies = ["install-slides", "install-book", "install-linkcheck", "install-formatter"] [tasks.install-book] -description = "Install dependencies for book tooling only." +description = "Install dependencies for building the book only." +category = "Install" +script = "cargo install --locked mdbook" + +[tasks.install-linkcheck] +description = "Install markup link checker (mlc)." +category = "Install" +script = "cargo install --locked mlc" + +[tasks.install-formatter] +description = "Install formatter (dprint)." category = "Install" -script = "cargo install mdbook" +script = "cargo install --locked dprint" [tasks.install-slides] description = "Install dependencies for slides tooling only." @@ -144,7 +153,6 @@ category = "Clean" script = "rm -rf html-slides" [tasks.img] -# FIXME want a native-to-rust way to invoke prettier, ideally without need for global install of https://prettier.io/docs/en/install.html category = "Checks" description = "Scan for image issues througout content." script = "./tools/scripts/orphan-image-scan.sh content/" @@ -154,16 +162,17 @@ category = "Checks" alias = "all-links" [tasks.all-links] -# FIXME want a native-to-rust way to invoke prettier, ideally without need for global install of https://prettier.io/docs/en/install.html category = "Checks" -description = "Check included links for all markdown files." -script = "yarn l" +description = "Check included links for all markup (.md|.html) files." +# FIXME .mlc.toml config not working... https://github.com/becheran/mlc/issues/78 +script = "mlc content/ --ignore-links '*slides.md,*slides.html,*twitter.com*,*sec.gov*,*support.giphy.com*,*bitdefender.com*,*etherscan.io*,*cryptoslate.com*,*golden.com*,'" [tasks.links-for] # FIXME want a native-to-rust way to invoke prettier, ideally without need for global install of https://prettier.io/docs/en/install.html category = "Checks" description = "Check links for specific file(s). Example: `makers links-for ./content/contribute/**/*.md`" -script = "yarn links-for ${@}" +# FIXME .mlc.toml config not working... https://github.com/becheran/mlc/issues/78 +script = "mlc ${@} --ignore-links '*slides.md,*slides.html,*twitter.com*,*sec.gov*,*support.giphy.com*,*bitdefender.com*,*etherscan.io*,*cryptoslate.com*,*golden.com*,'" [tasks.f] category = "Format" @@ -173,17 +182,7 @@ alias = "fmt" # FIXME want a native-to-rust way to invoke prettier, ideally without need for global install of https://prettier.io/docs/en/install.html category = "Format" description = "Format everything." -script = "yarn fmt" - -[tasks.fmt-book] -description = "Format the book source, only. (requires slides tooling installed)" -category = "Format" -script = "yarn fmt-book" - -[tasks.fmt-slides] -description = "Format the slides source, only." -category = "Format" -script = "yarn fmt-slides" +script = "dprint fmt" [tasks.catch-error] description = "Check and hint at solutions to common errors." @@ -197,7 +196,17 @@ if ! $(echo "type mdbook" | sh > /dev/null ) ; then exit 127 fi -if ! $(yarn --cwd ./slides-source/ --version > /dev/null) ; then +if ! $(echo "type mlc" | sh > /dev/null ) ; then + echo "\n❌ You may need to install the helpers tooling. Run:\n\nmarkers install\n\n***********" + exit 127 +fi + +if ! $(echo "type dprint" | sh > /dev/null ) ; then + echo "\n❌ You may need to install the helpers tooling. Run:\n\nmarkers install\n\n***********" + exit 127 +fi + +if ! $(yarn --version > /dev/null) ; then echo "\n❌ You may need to install the slides tooling. Run:\n\nmarkers slides-install\n" exit 127 fi diff --git a/content/CODE-OF-CONDUCT.md b/content/CODE-OF-CONDUCT.md index 8b4fcfd..7ed279f 100644 --- a/content/CODE-OF-CONDUCT.md +++ b/content/CODE-OF-CONDUCT.md @@ -59,8 +59,7 @@ representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -[INSERT CONTACT METHOD]. +reported to the community leaders responsible for enforcement at [academy@polkadot.network](mailto:academy@polkadot.network). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the diff --git a/content/LICENSE.md b/content/LICENSE.md index 64a6934..df28904 100644 --- a/content/LICENSE.md +++ b/content/LICENSE.md @@ -45,8 +45,8 @@ means having the right to grant, to the maximum extent possible, whether at the means any of the following: -1. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or -2. any new file in Source Code Form that contains any Covered Software. +1. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or +2. any new file in Source Code Form that contains any Covered Software. ### 1.11. “Patent Claims” of a Contributor @@ -70,8 +70,8 @@ means an individual or a legal entity exercising rights under this License. For Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: -1. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and -2. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. +1. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and +2. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. ### 2.2. Effective Date @@ -81,9 +81,9 @@ The licenses granted in Section 2.1 with respect to any Contribution become eff The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: -1. for any code that a Contributor has removed from Covered Software; or -2. for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or -3. under Patent Claims infringed by Covered Software in the absence of its Contributions. +1. for any code that a Contributor has removed from Covered Software; or +2. for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or +3. under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). @@ -113,8 +113,8 @@ All distribution of Covered Software in Source Code Form, including any Modifica If You distribute Covered Software in Executable Form then: -1. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and -2. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. +1. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and +2. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. ### 3.3. Distribution of a Larger Work diff --git a/content/blockchain-contracts/_materials/start-your-own-blockchain.md b/content/blockchain-contracts/_materials/start-your-own-blockchain.md index 6516418..602f835 100644 --- a/content/blockchain-contracts/_materials/start-your-own-blockchain.md +++ b/content/blockchain-contracts/_materials/start-your-own-blockchain.md @@ -10,11 +10,11 @@ See the README included in the repository for further instructions. ## Learning objectives: -1. How to run a node -1. What the log messages mean -1. Preview: How to configure a network with a chain spec -1. Experience peer connections coming and going -1. Practice checking for common not-peering issues (different genesis, firewall) +1. How to run a node +1. What the log messages mean +1. Preview: How to configure a network with a chain spec +1. Experience peer connections coming and going +1. Practice checking for common not-peering issues (different genesis, firewall) ## Outline diff --git a/content/blockchain-contracts/accounting/slides.md b/content/blockchain-contracts/accounting/slides.md index 53fbb47..7656c56 100644 --- a/content/blockchain-contracts/accounting/slides.md +++ b/content/blockchain-contracts/accounting/slides.md @@ -210,7 +210,8 @@ Did I forget any? Notes:" /> -Verify as opposed to determining the outcome. Not submitting output state in transaction +Verify as opposed to determining the outcome. +Not submitting output state in transaction --- diff --git a/content/blockchain-contracts/authoring/slides.md b/content/blockchain-contracts/authoring/slides.md index 8831b91..e00951d 100644 --- a/content/blockchain-contracts/authoring/slides.md +++ b/content/blockchain-contracts/authoring/slides.md @@ -30,7 +30,10 @@ Strong incentive alignments and strong guarantees make for high quality blockspa Notes: -As we discussed blockspace represents the right to contribute to the shared history. This is a valuable resource that is offered to users as a product. We will discuss the selling of this resource in a later lecture on allocation and fees. The consensus system used plays a large role in determining the quality of the blockspace. +As we discussed blockspace represents the right to contribute to the shared history. +This is a valuable resource that is offered to users as a product. +We will discuss the selling of this resource in a later lecture on allocation and fees. +The consensus system used plays a large role in determining the quality of the blockspace. --- @@ -38,17 +41,24 @@ As we discussed blockspace represents the right to contribute to the shared hist -There are going to be forks. We need to decide which one is the real one. +There are going to be forks. +We need to decide which one is the real one. -We can rule some forks out to reduce the problem space. Then we are left to decide which is canonical. +We can rule some forks out to reduce the problem space. +Then we are left to decide which is canonical. Notes: -Forks represent alternate courses that history could take. They arise every time there is a difference of opinion. +Forks represent alternate courses that history could take. +They arise every time there is a difference of opinion. -You can think of them at a social level. Court cases, arguments, wars. Ideally we can resolve them peacefully +You can think of them at a social level. +Court cases, arguments, wars. +Ideally we can resolve them peacefully -You can think of them at a very low physics-y level. Every time an electron encounters a potential barrier it either reflects of tunnels. When consensus is high-quality, the result is as objective as the outcome of a physical process. +You can think of them at a very low physics-y level. +Every time an electron encounters a potential barrier it either reflects of tunnels. +When consensus is high-quality, the result is as objective as the outcome of a physical process. --- @@ -66,9 +76,12 @@ You can think of them at a very low physics-y level. Every time an electron enco Notes: -The first two aspects are relatively simple and I'll discuss them briefly right now. The third and fourth are the main topic of this lecture. The fifth is covered in detail two lectures from now in great detail. +The first two aspects are relatively simple and I'll discuss them briefly right now. +The third and fourth are the main topic of this lecture. +The fifth is covered in detail two lectures from now in great detail. -The first three aspects are about ruling possibilities out. The fourth and fifth are about deciding between any remaining possibilities. +The first three aspects are about ruling possibilities out. +The fourth and fifth are about deciding between any remaining possibilities. ---v @@ -80,13 +93,15 @@ Some forks can be ruled out simply because they contain invalid state transition Notes: -Example spending more money than you have. Noting your present location such that you would have traveled faster than speed of light since last record. Calling a smart contract with invalid parameters. +Example spending more money than you have. +Noting your present location such that you would have traveled faster than speed of light since last record. +Calling a smart contract with invalid parameters. ---v ## Arbitrary / Political Validity -Similar to state machine validity.
+Similar to state machine validity.
Examples: @@ -102,7 +117,10 @@ Examples: Notes: -This concept is similar to the previous slide. In some sense this is even the same. This allows us to rule out some forks just for not having properties that we like. Or for having properties that we dislike. +This concept is similar to the previous slide. +In some sense this is even the same. +This allows us to rule out some forks just for not having properties that we like. +Or for having properties that we dislike. Not everyone will agree on these properties ad that leads to long-term network splits. @@ -110,14 +128,22 @@ Not everyone will agree on these properties ad that leads to long-term network s ## Authorship Throttling -Real-world blockchains impose additional restrictions on who can author blocks. Why? +Real-world blockchains impose additional restrictions on who can author blocks. +Why? Notes: -These blockchains are supposed to be permissionless right? At least many of them are. Some are even very hardcore about that goal. So why would we want to restrict the authoring. -Answer: So the nodes are not overwhelmed. Unthrottled authoring leads to fork chaos. If anyone authored at any moment there would be blocks raining down left and right. It would be impossible to check them all. It would be DOS central. So we need some organization / order to the process. +These blockchains are supposed to be permissionless right? At least many of them are. +Some are even very hardcore about that goal. +So why would we want to restrict the authoring. +Answer: So the nodes are not overwhelmed. +Unthrottled authoring leads to fork chaos. +If anyone authored at any moment there would be blocks raining down left and right. +It would be impossible to check them all. +It would be DOS central. +So we need some organization / order to the process. ---v @@ -139,7 +165,10 @@ The ability of the system to keep authoring new blocks Notes: -Before we go on, I want to introduce the concept of liveness. It is a desireable property that consensus systems want to have. Systems that have better liveness properties offer higher quality blockspace. Chains without liveness guarantees become stalled. +Before we go on, I want to introduce the concept of liveness. +It is a desireable property that consensus systems want to have. +Systems that have better liveness properties offer higher quality blockspace. +Chains without liveness guarantees become stalled. --- @@ -164,13 +193,20 @@ Solve a Pre-image search - earn the right to author. Notes: -On the surface one big strength of PoW is that anyone can spin up a node and join at any time without anyone's permission. This is clearly how it was described in the whitepaper. In practice, many systems now have such a high hashrate that your home computer is useless. It is now permissioned by who can afford and acquire the right hardware. +On the surface one big strength of PoW is that anyone can spin up a node and join at any time without anyone's permission. +This is clearly how it was described in the whitepaper. +In practice, many systems now have such a high hashrate that your home computer is useless. +It is now permissioned by who can afford and acquire the right hardware. -The reliance on an external resource is good in some sense because it is an objective measure of the market's valuation of the consensus system. This helps valuate the blockspace. +The reliance on an external resource is good in some sense because it is an objective measure of the market's valuation of the consensus system. +This helps valuate the blockspace. The blindness is a good property because it makes it impossible to perform a targeted attack (DOS or physical) on the next leader to stall the network. -Some attacks rely on the leader authoring two competing forks and gossiping them to different parts of the network. With PoW, it costs energy for every block you author. This makes it expensive to perform such attacks. This provides an economic incentive for authors to only author blocks on the "correct" fork. +Some attacks rely on the leader authoring two competing forks and gossiping them to different parts of the network. +With PoW, it costs energy for every block you author. +This makes it expensive to perform such attacks. +This provides an economic incentive for authors to only author blocks on the "correct" fork. ---v @@ -186,11 +222,16 @@ Some attacks rely on the leader authoring two competing forks and gossiping them Notes: -Energy consumption is more often considered a negative property. Sometimes called proof of _waste_. I won't go that far, but in a world where climate change is a reality, it is certainly not ideal to be spending so much energy if we can get away with far less. +Energy consumption is more often considered a negative property. +Sometimes called proof of _waste_. +I won't go that far, but in a world where climate change is a reality, it is certainly not ideal to be spending so much energy if we can get away with far less. -Worth noting that some PoW schemes (eg Monero's) strive to minimize the energy impact by choosing algorithms that are "asic resistant". While these are decidedly better than Bitcoin's, they do not fundamentally solve the problem. Just alleviate it somewhat in practice. +Worth noting that some PoW schemes (eg Monero's) strive to minimize the energy impact by choosing algorithms that are "asic resistant". +While these are decidedly better than Bitcoin's, they do not fundamentally solve the problem. +Just alleviate it somewhat in practice. -Secondly, the block time is only probabilistically known. When waiting for block to be authored, there are sometimes spurts of blocks followed by long stretches without any. +Secondly, the block time is only probabilistically known. +When waiting for block to be authored, there are sometimes spurts of blocks followed by long stretches without any. Although it seems permissionless on its face, in practice, to be a bitcoin miner you need to have expensive specialized hardware. @@ -206,7 +247,10 @@ Notes: If it costs energy to author blocks, why would anyone want to author to begin with? -Mining only when you want to get your transaction in seems like a good idea to me. People who don't want to self author, can pay other a fee to do it for them. This is the purpose of transaction fees. Most chains have transaction fees specified in the transactions themselves which go to the author +Mining only when you want to get your transaction in seems like a good idea to me. +People who don't want to self author, can pay other a fee to do it for them. +This is the purpose of transaction fees. +Most chains have transaction fees specified in the transactions themselves which go to the author Some networks also add an explicit incentives such as a 50BTC reward per block. @@ -235,7 +279,9 @@ Prove your identity with a signature. Notes: -Stable block time is a property of high-quality block space. It allows applications that consume the blockspace to have expectations about throughput. In PoW you will occasionally have long periods without a block which can negatively affect applications. +Stable block time is a property of high-quality block space. +It allows applications that consume the blockspace to have expectations about throughput. +In PoW you will occasionally have long periods without a block which can negatively affect applications. ---v @@ -251,7 +297,8 @@ Stable block time is a property of high-quality block space. It allows applicati Notes: -Does anything bad happen if they misbehave? Not inherently. We will need an incentive for that. +Does anything bad happen if they misbehave? Not inherently. +We will need an incentive for that. --- @@ -289,12 +336,9 @@ Cons: **B**lind **A**ssignment for **B**lockchain **E**xtension - In each slot, compute a VRF output. -- If it is below a threshold, you are eligible to author. - -- If eligible, author a block showing VRF proof - -- If NOT eligible, do nothing - +- If it is below a threshold, you are eligible to author. +- If eligible, author a block showing VRF proof +- If NOT eligible, do nothing Notes: @@ -304,8 +348,8 @@ Pros: Cons: -- Some slots have no authors - There is a workaround for this -- Other slots have multiple authors which leads to forks. There is no workaround for this +- Some slots have no authors - There is a workaround for this. +- Other slots have multiple authors which leads to forks - There is **no** workaround for this. ---v @@ -389,9 +433,15 @@ Restores clear economic incentives Notes: -There is an economic game called staking as part of the state machine that allows selecting the authorities who will participate in the PoA scheme. Actually there isn't just _one_ way to do it, there are many. Kian will talk a lot more about this and about the way it is done in Polkadot later. I'll just give the flavor now. +There is an economic game called staking as part of the state machine that allows selecting the authorities who will participate in the PoA scheme. +Actually there isn't just _one_ way to do it, there are many. +Kian will talk a lot more about this and about the way it is done in Polkadot later. +I'll just give the flavor now. -The basic idea is that anyone can lock up some tokens on chain (in the state machine). The participants with the most tokens staked are elected as the authorities. There is a state transition that allows reporting authority misbehavior (eg authoring competing blocks at the same height), and the authority loses their tokens. There are often block rewards too like PoW. +The basic idea is that anyone can lock up some tokens on chain (in the state machine). +The participants with the most tokens staked are elected as the authorities. +There is a state transition that allows reporting authority misbehavior (eg authoring competing blocks at the same height), and the authority loses their tokens. +There are often block rewards too like PoW. ---v @@ -407,7 +457,13 @@ In Substrate there is a concept of a **Runtime API** - Consensus can read inform Notes: -So far I've presented consensus as orthogonal to the state machine. This is mostly true. But in practice it is extremely common for there to be some loose coupling. We already saw an example when we talked about block rewards. The consensus authors are rewarded with tokens (in the state machine) for authoring blocks. Now we see that they can have tokens slashed (in state machine) for breaking consensus protocol. And we see that even the very authorities can be elected in the state machine. +So far I've presented consensus as orthogonal to the state machine. +This is mostly true. +But in practice it is extremely common for there to be some loose coupling. +We already saw an example when we talked about block rewards. +The consensus authors are rewarded with tokens (in the state machine) for authoring blocks. +Now we see that they can have tokens slashed (in state machine) for breaking consensus protocol. +And we see that even the very authorities can be elected in the state machine. --- @@ -428,7 +484,9 @@ Each node's preference for which fork is best Notes: -The fork choice allows you, as a network participant, to decide which fork you consider best for now. It is not binding. Your opinion can change as you see more blocks appear on the network +The fork choice allows you, as a network participant, to decide which fork you consider best for now. +It is not binding. +Your opinion can change as you see more blocks appear on the network ---v @@ -442,12 +500,19 @@ Dropped transactions re-enter tx pool and re-appear in new blocks shortly + - Efficiency + + - Tool Simplicity + + - Support as Compilation Target + + - Sandboxing + Notes: @@ -268,10 +278,15 @@ Those things can't be addressed by the PAB itself but they can give good guideli - Rust, C, C++ and many others - Fast (with near-native performance) + + - Safe (executed in a sandboxed environment) + + - Open (programs can interoperate with their environment) + @@ -338,7 +353,8 @@ Wat has some features that allow for better readability: - Labels can be applied to elements. - Blocks can enclosed with parenthesis instead of explicit start/end instructions. -Instructions push results to the stack and use values on the stack as arguments, the compilation process generally translate this stack-based bytecode to register based, where registers are used to pass values to instructions as a primary mechanism. The compilation will try to elide the wasm stack and work with only the architecture registers. +Instructions push results to the stack and use values on the stack as arguments, the compilation process generally translate this stack-based bytecode to register based, where registers are used to pass values to instructions as a primary mechanism. +The compilation will try to elide the wasm stack and work with only the architecture registers. There is another type of stack used in wasm and that's called: shadow stack, resource to learn more: @@ -347,10 +363,15 @@ There is another type of stack used in wasm and that's called: shadow stack, res ## Wasm seems to be a perfect PAB, but - How does communication with the environment work? + + - How the memory is managed? + + - How is it executed? + Notes: @@ -430,9 +451,11 @@ The Rust compiler uses for dynamic/heap memory and to pass non primitives values Notes: -Here's an example, wasm sees linear memory like a byte array and if it tries to access the second byte, it would use an index 1. When it's time to execute it the embedder will see this access and translate the linear memory access at index 1 to a standard memory access to base_linear_memory + 1. +Here's an example, wasm sees linear memory like a byte array and if it tries to access the second byte, it would use an index 1. +When it's time to execute it the embedder will see this access and translate the linear memory access at index 1 to a standard memory access to base_linear_memory + 1. -Buffer overflow? Wasm uses 32 bit, this makes impossible to have an offset bigger then 4GiB, this means that the embedder can leave those 4GiB free in its virtual memory to makes impossible to the wasm blob to access any environment information. Even if the offset is only positive there are embedded that are defining as protected the 2GiB before the BLM so that if for some reason the wasm code trick the embedder to treat the offset as a signed number that would cause an Operating System error. +Buffer overflow? Wasm uses 32 bit, this makes impossible to have an offset bigger then 4GiB, this means that the embedder can leave those 4GiB free in its virtual memory to makes impossible to the wasm blob to access any environment information. +Even if the offset is only positive there are embedded that are defining as protected the 2GiB before the BLM so that if for some reason the wasm code trick the embedder to treat the offset as a signed number that would cause an Operating System error. --- @@ -474,7 +497,8 @@ Notes: - wasmtime book: - Used in substrate as embedder for the blockchain logic -Cranelift is a fast, secure, relatively simple and innovative compiler backend. It takes an intermediate representation of a program generated by some frontend and compiles it to executable machine code +Cranelift is a fast, secure, relatively simple and innovative compiler backend. +It takes an intermediate representation of a program generated by some frontend and compiles it to executable machine code ---v @@ -506,7 +530,7 @@ Notes: proposal to switch from a stack based ir to registry based ir -paper explaining the efficiency of translating wasm to registry based code +paper explaining the efficiency of translating wasm to registry based code Due to it's characteristics it is mainly used to execute SmartContracts on chain @@ -532,7 +556,6 @@ There are also light clients, where both Runtime and Client are implemented in w - the node's client as embedder for the node's runtime - the node's runtime as embedder for the SmartContract - We have a double recursion of a PAB that embed itself diff --git a/content/blockchain-contracts/coordination-trust/slides.md b/content/blockchain-contracts/coordination-trust/slides.md index 45f2c3b..b9a5c58 100644 --- a/content/blockchain-contracts/coordination-trust/slides.md +++ b/content/blockchain-contracts/coordination-trust/slides.md @@ -7,7 +7,6 @@ description: Principles of coordination, contracts, smart contracts, and compari Notes: -Intro In this module we're going to talk about Smart Contracts. --- @@ -24,11 +23,12 @@ _aka Szabo definition_ +Personal trust - you can build it over time through a slow give and take like you do with your family or long term business partners. Notes: @@ -232,10 +235,10 @@ Anyone? (check for nods) _So, some personal historical context on me_, when I was a newbie in the web3 space, I hadn’t heard this phrase (or slogan rather?). I saw it on ppl’s shirts and felt sort of confused and honestly, kind of excluded from what felt like maybe an inside joke. -I remember thinking, _wait, I trust people, does that make me wrong? Is that a bad thing?_ -I asked myself the question, _why is trust such a dirty world in our world?_ +I remember thinking, _wait, I trust people, does that make me wrong... Is that a bad thing_? +I asked myself the question, _why is trust such a dirty world in our world_? Well, in time, thanks to some of my fellow instructors in the room, I came to understand that this phrase is referring to the fact that life is not all sunshine and roses! Not all relationships and interactions are filled with trustful actors. -In fact, most aren't! +In fact, most aren't! Literally every day we're in situations in which we are forced to treat complete strangers as if we've established real, authentic trust between one another. Treat them as if they're a close friend or business partner. And _that_ is definitely bad, and is a dirty word, and is a thing that we really shouldn't do. @@ -261,7 +264,7 @@ So. We know that we don't have the luxury of only interacting with people we truly personally trust. It's impossible to get personal trust with every person you'd in theory like to because it takes a super long time to bootstrap that real kind of relationship. And frankly, sometimes you want to interact with a stranger more immediately, say today, and not have to court them for years upon years. -So, again, this should lead us to the question of - how do you handle these every day situations? How DO I trust that the coffee guy isn't going to run off with my credit card details? +So, again, this should lead us to the question of - how do you handle these every day situations? How DO I trust that the coffee guy isn't going to run off with my credit card details? CLICK - Well, that's where rational expectations come into play. This is a game theory, incentives-based concept. Where you believe credibly that a person _will_ act faithfully according to an agreement you've made - because the incentives make them do so. @@ -278,7 +281,7 @@ Notes: Again, I want to make sure you're all hearing me when I say that personal/familial trust is not wrong, or bad, or dirty. I don’t want us all walking out here calling our moms and dissolving our trust with them. -That just isn’t the scenario we speak to when we say 'trust is dirty' +That just isn’t the scenario we speak to when we say 'trust is dirty'. And further, if you have someone who you genuinely trust, you can actually get things done a whole lot faster and more efficiently by leveraging that trust. So, it may be worth it to bootstrap genuine personal trust. You know, start small, accept a small bit of risk and gradually increase that over time. @@ -304,7 +307,7 @@ Often they are civic duty based - the fear that society or your town will turn o OR they're morality or religion based - you know, you keep your promise to someone out of fear of otherwise going to hell. Or they are based on the fact that you have a reputation to uphold. You don't want to be known as a liar or a cheat. -I think you get what I'm saying here, yeah? +I think you get what I'm saying here, yeah? It's social norms and expectations that keep people. Reputation is on the line. And this can get society pretty far. @@ -344,7 +347,7 @@ I think this is his way of saying that we need some bigger and more resilient co Notes: -So how do we incentivize people to keep their promises beyond a civic duty? +So how do we incentivize people to keep their promises beyond a civic duty? Ding ding ding - Finally! This brings us to the idea of contracts. They're basically, pretty much, promises. They could involve money, a lot of them do, though they don't have to. @@ -414,10 +417,11 @@ Notes: So yeah, that's the goal and what we're trying to solve. But, again, just before we go any further, let’s make sure we’re all on the same page about what a contract itself is. A promise, made between parties, backed by the government, to coordinate together to accomplish something together. -The notion of promise is very abstract: -It could involve coordinating over time. -It could involve money or even credit. -It also could have multiple possible valid outcomes. +The notion of promise is very abstract: + +- It could involve coordinating over time. +- It could involve money or even credit. +- It also could have multiple possible valid outcomes. Okay. Cool. @@ -441,9 +445,7 @@ And together we'll develop and tease out those same comparisons here.
A machine program with rules that we could have defined in a contract, but instead a machine performs or verifies performance.
-Broad definition -_aka Szabo definition_ -formulated c 1997 +Broad definition _aka Szabo definition_ formulated c 1997 Notes: @@ -667,7 +669,7 @@ Multiple controllers and multiple physically present users. The internet makes it better in some ways. We can interact with our smart contract remotely instead of being physically present. But now, there is the question of the server operator. -Are they really executing the correct contract? +Are they really executing the correct contract? A corrupt server operator is essentially the same as a corrupt judge. Hmmm... so I wonder how we might solve this? @@ -684,7 +686,7 @@ So, after all of that talk comparing law and code, it's inevitable that we get h We know tech can be used to enforce rules. So we might wonder, do we actually need lawyers? Can code dictate what we can and cannot do? Can smart contracts be the answer? I'm not coming for lawyers. I'm sure they're nice. -But could this be the answer to make life more trustless and secure? +But could this be the answer to make life more trustless and secure? But this is where we'll end it today. I hope I've primed you with a few lingering questions. These smart contracts do sound cool, but perhaps the execution, where it actually happens, hopefully is a bit opaque and puzzling still. diff --git a/content/blockchain-contracts/dag/slides.md b/content/blockchain-contracts/dag/slides.md index 7df0559..c58a0bf 100644 --- a/content/blockchain-contracts/dag/slides.md +++ b/content/blockchain-contracts/dag/slides.md @@ -9,7 +9,7 @@ description: A formal, yet friendly consensus framework ## Goals of this lecture -
+
1. formalize the consensus problem and related concepts 2. provide a framework for designing DAG-based consensus protocols @@ -18,7 +18,7 @@ description: A formal, yet friendly consensus framework ## What is consensus? -
+
- a **process** of agreeing on the same result among a group of participants - a fundamental **problem** in distributed computing @@ -28,7 +28,7 @@ description: A formal, yet friendly consensus framework ## Consensus features -
+
liveness, safety, integrity @@ -36,7 +36,7 @@ liveness, safety, integrity ## We have already seen some -
+
Nakamoto @@ -54,7 +54,7 @@ Tendermint ## Who is running the protocol? -
+
Participants, called **nodes** @@ -62,7 +62,7 @@ Participants, called **nodes** ## Nodes -
+
- nodes can be either honest or malicious - honest nodes follow the protocol @@ -74,7 +74,7 @@ Participants, called **nodes** ## Public key infrastructure -
+
- every node has its own private and public key - every node signs messages with its private key @@ -84,7 +84,7 @@ Participants, called **nodes** ## Public key infrastructure -
+
authenticated point-to-point communication @@ -92,7 +92,7 @@ authenticated point-to-point communication ## Adversary -
+
Adversary **can** control the network delays, but is _computationally bounded_, i.e. it **cannot** break the cryptography (like forging the signatures). @@ -100,7 +100,7 @@ Adversary **can** control the network delays, but is _computationally bounded_, ## Network -
+
Communication via network... but what kind of network? @@ -108,7 +108,7 @@ Communication via network... but what kind of network? ## Network models -
+
synchronous @@ -120,12 +120,12 @@ asynchronous ## Network models: synchronous -
+
> There exists a known upper bound \\(\Delta\\) on message delivery time. -
-
+
+
_Intuition: there's a well-defined notion of a protocol round_ @@ -133,12 +133,12 @@ _Intuition: there's a well-defined notion of a protocol round_ ## Network models: asynchronous -
+
> There is no upper bound on message delay, though delivery is guaranteed. -
-
+
+
_Intuition: you can't tell whether a node has crashed or has a long delay_ @@ -146,12 +146,12 @@ _Intuition: you can't tell whether a node has crashed or has a long delay_ ## Network models: asynchronous -
+
> There is no upper bound on message delay, though delivery is guaranteed. -
-
+
+
- We assume that the adversary has full control over the message delays. - The concept of a timeout is basically useless. @@ -160,12 +160,12 @@ _Intuition: you can't tell whether a node has crashed or has a long delay_ ## Network models: partially synchronous -
+
> There exists a known bound \\(\Delta\\), and an unknown point in time **GST** after which the communication becomes synchronous with a delay \\(\Delta\\). -
-
+
+
_Intuition: protocol will eventually work synchronously, but it needs to be safe before_ @@ -173,39 +173,39 @@ _Intuition: protocol will eventually work synchronously, but it needs to be safe ## Crucial theoretical results -
+
-> [FLP theorem] It is impossible to have a deterministic protocol that solves consensus in an asynchronous system in which at least one process may fail by crashing. +> \[FLP theorem\] It is impossible to have a deterministic protocol that solves consensus in an asynchronous system in which at least one process may fail by crashing. -
-
+
+
-> [Castro-Liskov theorem] It is impossible to have a protocol that solves consensus in a partially synchronous system with \\(3f+1\\) nodes in which more than \\(f\\) processes are byzantine. +> \[Castro-Liskov theorem\] It is impossible to have a protocol that solves consensus in a partially synchronous system with \\(3f+1\\) nodes in which more than \\(f\\) processes are byzantine. --- ## Crucial theoretical results -
+
-> [FLP theorem] It is impossible to have a deterministic protocol that solves consensus in an asynchronous system in which at least one process may fail by crashing. +> \[FLP theorem\] It is impossible to have a deterministic protocol that solves consensus in an asynchronous system in which at least one process may fail by crashing. -
-
+
+
-> [Castro-Liskov theorem] It is impossible to have a protocol that solves consensus in a partially synchronous system with \\(3f+1\\) nodes in which more than \\(f\\) processes are byzantine. +> \[Castro-Liskov theorem\] It is impossible to have a protocol that solves consensus in a partially synchronous system with \\(3f+1\\) nodes in which more than \\(f\\) processes are byzantine. --- ## Consequence -
+
The best one can hope for in **asynchronous** scenario is **probabilistic** protocol tolerating **up to** \\(f\\) faults for \\(3f+1\\) participants. -
+
-> ✅ **Doable!** +> ✅ **Doable!** @@ -213,7 +213,7 @@ The best one can hope for in **asynchronous** scenario is **probabilistic** prot ## Note on randomness -
+
Real probability is actually needed in the extremely hostile environment. In case where the adversary is not legendarily vicious, even a dumb (but non-trivial) randomness source will do. @@ -226,20 +226,20 @@ In case where the adversary is not legendarily vicious, even a dumb (but non-tri ## Responsiveness -
+
Protocols that are **not responsive** have to **wait for** \\(\Delta\\) **time** to proceed to the next round. -
+
--- ## Responsiveness -
+
Protocols that are **not responsive** have to **wait for** \\(\Delta\\) **time** to proceed to the next round. -
-
+
+
- \\(\Delta\\) must be long enough to allow all honest nodes to send their messages. - \\(\Delta\\) must be short enough to allow the protocol to make progress. @@ -249,12 +249,12 @@ Protocols that are **not responsive** have to **wait for** \\(\Delta\\) **time** ## Responsiveness -
+
Protocols that are **responsive** **wait for** \\(2f+1\\) **messages** to proceed to the next round. -
-
+
+
> Why \\(2f+1\\)? @@ -264,12 +264,12 @@ Protocols that are **responsive** **wait for** \\(2f+1\\) **messages** to procee ## Responsiveness -
+
Protocols that are **responsive** **wait for** \\(2f+1\\) **messages** to proceed to the next round. -
-
+
+
> Among \\(2f+1\\) nodes, there are at least \\(f+1\\) honest ones, i.e. honest majority. @@ -277,11 +277,11 @@ Protocols that are **responsive** **wait for** \\(2f+1\\) **messages** to procee ## Responsiveness -
+
Protocols that are **responsive** **wait for** \\(2f+1\\) **messages** to proceed to the next round. -
-
+
+
- Asynchronous protocols must be responsive. - In good network conditions, they significantly much faster. @@ -290,7 +290,7 @@ Protocols that are **responsive** **wait for** \\(2f+1\\) **messages** to procee ## Checkpoint -
+
Up to this point, we covered: @@ -305,12 +305,12 @@ Up to this point, we covered: ## Warmup exercise: broadcast -
+
> (In an asynchronous network) **reliably** send a single message to all other nodes. -
-
+
+
- (_validity_) If the sender is honest and broadcasts a message \\(m\\), then every honest node outputs \\(m\\). @@ -328,7 +328,7 @@ Up to this point, we covered: ## Reliable broadcast protocol (RBC) -
+
@@ -336,7 +336,7 @@ Up to this point, we covered: ## Reliable broadcast in practice -
+
Due to the very high communication complexity we use heuristics or cryptography-based tricks. @@ -344,10 +344,10 @@ Due to the very high communication complexity we use heuristics or cryptography- ## Blockchain protocol vs Atomic broadcast -
+
Atomic broadcast -
+
@@ -355,10 +355,10 @@ Atomic broadcast ## Randomness formalized -
+
Randomness beacon -
+
@@ -366,7 +366,7 @@ Randomness beacon ## Atomic broadcast: timeline -
+
@@ -374,7 +374,7 @@ Randomness beacon ## Atomic broadcast: timeline -
+
@@ -382,7 +382,7 @@ Randomness beacon ## Fun fact -
+
Aleph paper, as the first, also achieved fully asynchronous randomness beacon: @@ -393,36 +393,36 @@ Aleph paper, as the first, also achieved fully asynchronous randomness beacon: ## Consensus protocols (selection) -
+
### Classical protocols: -- [DLS’88], [CR’92], -- PBFT [CL’99] -- Random Oracles … [CKS’05] -- Honey Badger BFT [MXCSS’16] -- Tendermint [BKM’18] -- VABA [AMS’19] -- Flexible BFT [MNR’19] -- HotStuff [YMRGA’19] -- Streamlet [CS’20] -- Grandpa [SKK'20] +- \[DLS’88\], \[CR’92\], +- PBFT \[CL’99\] +- Random Oracles … \[CKS’05\] +- Honey Badger BFT \[MXCSS’16\] +- Tendermint \[BKM’18\] +- VABA \[AMS’19\] +- Flexible BFT \[MNR’19\] +- HotStuff \[YMRGA’19\] +- Streamlet \[CS’20\] +- Grandpa \[SKK'20\] ### DAG-based protocols: -- [L. Moser, P. Meliar-Smith ‘99] -- Hashgraph [B’16] -- Aleph [GLSS’18] -- DAG-Rider [KKNS’21] -- Highway [KFGS’21] -- Narwhal&Tusk [DKSS’22] -- Bullshark [SGSK’22] +- \[L. Moser, P. Meliar-Smith ‘99\] +- Hashgraph \[B’16\] +- Aleph \[GLSS’18\] +- DAG-Rider \[KKNS’21\] +- Highway \[KFGS’21\] +- Narwhal&Tusk \[DKSS’22\] +- Bullshark \[SGSK’22\] @@ -435,10 +435,10 @@ Aleph paper, as the first, also achieved fully asynchronous randomness beacon: ## DAG -
+
Directed Acyclic Graph -
+
@@ -446,10 +446,10 @@ Directed Acyclic Graph ## How does it relate to consensus? -
+
Intuition: graph represents the dependencies between messages (units). -
+
@@ -457,7 +457,7 @@ Intuition: graph represents the dependencies between messages (units). ## Framework core -
+
1. We maintain a local DAG representing our knowledge of the units. 2. We perform a local, offline consensus on our DAG. @@ -466,16 +466,16 @@ Intuition: graph represents the dependencies between messages (units). ## Framework core -
+
1. We maintain a local DAG representing our knowledge of the units. -2. We perform a local, **offline consensus** on our DAG. +2. We perform a local, **offline consensus** on our DAG. --- ## Framework core (in other words) -
+
1. (online): sending and receiving units that contribute to the local DAG 2. (offline): everybody performs a local consensus on the DAG, just by looking at it @@ -484,7 +484,7 @@ Intuition: graph represents the dependencies between messages (units). ## Clue observations -
+
- local DAGs might differ... - but they are guaranteed to converge to the same DAG @@ -494,7 +494,7 @@ Intuition: graph represents the dependencies between messages (units). ## Adversary control -
+
@@ -502,7 +502,7 @@ Intuition: graph represents the dependencies between messages (units). ## Randomness? Where is randomness? -
+
It is put into the local consensus protocol. @@ -510,7 +510,7 @@ It is put into the local consensus protocol. ## Relation to the atomic consensus problem -
+
- nodes receive transactions and put them into units - nodes send each other their new units @@ -520,14 +520,14 @@ It is put into the local consensus protocol. ## Digression: block production, information dissemination and finalization -
+
The common approach (e.g. in Substrate): - production and dissemination is done in the same layer - afterwards, nodes perform consensus on finalizing disseminated blocks -
+
Natural approach for DAG-based protocols: @@ -538,7 +538,7 @@ Natural approach for DAG-based protocols: ## Main consequences of the different separation -
+
- block signatures - speed @@ -547,7 +547,7 @@ Natural approach for DAG-based protocols: ## Local consensus: goal -
+
Local copies might differ significantly, blocks might have not come to all nodes yet, etc... but we have to make common decision about unit ordering! @@ -556,11 +556,11 @@ but we have to make common decision about unit ordering! ## Key concept: availability -
+
Intuitively, a unit is **available** if: -
+
- most of the nodes have it - it was distributed pretty promptly (we won't call a unit available, if it finally arrived everywhere after a month) @@ -570,7 +570,7 @@ Intuitively, a unit is **available** if: ## Availability -
+
If a unit is available, it is a good candidate for being chosen as an 'anchor' in extending current ordering. @@ -578,7 +578,7 @@ If a unit is available, it is a good candidate for being chosen as an 'anchor' i ## Lightweight case study -
+
Aleph Zero BFT protocol @@ -586,7 +586,7 @@ Aleph Zero BFT protocol ## Head -
+
@@ -594,7 +594,7 @@ Aleph Zero BFT protocol ## Building blocks -
+
@@ -602,7 +602,7 @@ Aleph Zero BFT protocol ## Choosing head -
+
@@ -610,7 +610,7 @@ Aleph Zero BFT protocol ## Availability determination -
+
Units vote for each other's availability. @@ -618,15 +618,15 @@ Units vote for each other's availability. ## (Part of) availability determination -
+
VoteU(V) = - \[\[U is parent of V\]\] if V is from the round just after the round of U - `0`/`1` if all children of U voted `0`/`1` -- `CommonVote(round(`U`), round(`V`))` otherwise -
-
+- `CommonVote(round(`U `), round(`V `))` otherwise +
+
_(U comes from the earlier round than V)_ @@ -634,12 +634,12 @@ _(U comes from the earlier round than V)_ ## Bonus: generating randomness -
+
-Sig`sk`(nonce) +Sig `sk`(nonce) -
+
@@ -654,7 +654,7 @@ Sig`sk`(nonce) ## Standard way -
+
@@ -662,7 +662,7 @@ Sig`sk`(nonce) ## Standard way -
+
@@ -672,7 +672,7 @@ Problem: need for trusted dealer! ## One simple trick -
+
Everybody is dealing secrets @@ -680,6 +680,6 @@ Problem: need for trusted dealer! ## Combining randomness -
+
diff --git a/content/blockchain-contracts/econ-game-theory/slides.md b/content/blockchain-contracts/econ-game-theory/slides.md index 26041aa..d246ca8 100644 --- a/content/blockchain-contracts/econ-game-theory/slides.md +++ b/content/blockchain-contracts/econ-game-theory/slides.md @@ -533,7 +533,7 @@ Things like Twitter, Facebook or Bitcoin are often deemed as valuable because of ## Nash Equilibrium -
+
#### _Network Effect_ @@ -551,11 +551,11 @@ In blockchains if more people use your chain it's more valuable. ## Nash Equilibrium -
+
#### _Network Effect_ -
+
Assumptions revisited:
  • Only 2 miners
  • @@ -695,10 +695,10 @@ But what if we change the assumptions a bit? ## Nash Equilibrium -
    +
    What does it mean exactly to be dishonest? -
    -
    +
    +
    There are some mainstream rules (the protocol) and if an individual miner breaks them it seems like an isolated @@ -706,8 +706,8 @@ What does it mean exactly to be dishonest?
    -
    -
    +
    +
    If multiple miners break the protocol in the same way, it can be seen as a new protocol deviating from the main one. @@ -828,8 +828,8 @@ And in fact what we have in here is two distinct Nash Equilibria! So is being honest the best strategy? -
    -
    +
    +
    Not always. If the majority of people are honest then honesty pays off. @@ -838,8 +838,8 @@ same way then be _dishonest_ with them. -
    -
    +
    +
    In fact it was proven that in PoW following the majority is the true Nash Equilibrium no matter what strategy/protocol they are using as long as it's consistent. @@ -881,6 +881,7 @@ What if we have multiple Nash Equilibria? Schelling point often comes to the res - A solution that people tend to choose (easiest to coordinate on) - Generally it is also a Nash Equilibrium - How in the world can it be useful in Blockchain? + Notes: @@ -974,8 +975,8 @@ And this concept is vital to something in blockchain called... #### _Oracles_ Oracles are blockchain entities that provide information from the outside world to the blockchain. -
    -
    +
    +
    Oracle getting information from real world Notes: @@ -992,8 +993,8 @@ And that's a very very hard task. #### _Oracles_ Oracles are blockchain entities that provide information from the outside world to the blockchain. -
    -
    +
    +
    External Information Examples: @@ -1016,8 +1017,8 @@ Let's actually see how they might work is a slightly simplified version with the #### _Oracles_ -
    -
    +
    +
    Temperature Line Notes: @@ -1034,8 +1035,8 @@ But what it is exactly? #### _Oracles_ -
    -
    +
    +
    Temperature Line with Some Measurements Notes: @@ -1094,7 +1095,7 @@ Submitting the truth is the Schelling Point in here and it makes it easy to be h - What to do with attackers? + What to do with attackers? Temperature Line with a Cluster of Measurements @@ -1113,8 +1114,8 @@ But what if there are some attackers? What can we do about them? - What to do with attackers? -

    + What to do with attackers? +

    If they go unpunished they can repeat the attack until successful
    @@ -1135,11 +1136,11 @@ And that's not good. - What to do with attackers? -

    + What to do with attackers? +

    If they go unpunished they can repeat the attack until successful -

    - Or even worse, they can make a million fake identities and spam incorrect votes +

    + Or even worse, they can make a million fake identities and spam incorrect votes
    Temperature Line with a Cluster of Measurements @@ -1170,7 +1171,7 @@ And they are vital to the blockchain space. ## Incentives _"Something that encourages a person to do something."_ -

    +

    In our case we want to shape incentives that motivate the users to submit honest values.
    @@ -1192,11 +1193,11 @@ We need to build out incentives in a way that shapes the expected behavior of th - What to do with attackers? -

    + What to do with attackers? +

    If they go unpunished they can repeat the attack until successful -

    - Or even worse, they can make a million fake identities and spam incorrect votes +

    + Or even worse, they can make a million fake identities and spam incorrect votes
    Temperature Line with a Cluster of Measurements @@ -1215,10 +1216,10 @@ So going back to our oracle problem how can we deal with attackers? -
    What to do with attackers? -

    +
    What to do with attackers? +

    If they go unpunished they can repeat the attack until successful -

    +

    Or even worse, they can make a million fake identities and spam incorrect votes
    @@ -1240,9 +1241,9 @@ How can we prevent that? Sybil Attacks -

    +

    Common problem in blockchain. -

    +

    If deploying on a chain, an easy solution is to make users lock some funds.
    @@ -1273,9 +1274,9 @@ This is a very simple solution but it's not always applicable.
    What to do with attackers?
    -
    +
    If they go unpunished they can repeat the attack until successful -

    +

    Or even worse, they can make a million fake identities and spam incorrect votes
    @@ -1297,11 +1298,11 @@ How can we deal with them so they don't continue attacking us? Punishments -

    +

    We already laid out the foundation for punishments. -

    +

    Our solution for de-sybiling users makes them lock funds. -

    +

    If such a user would vote incorrectly, we can slash their funds.
    @@ -1330,10 +1331,10 @@ We have designed some protective incentives and now the system seems safe. #### _Oracles_ -
    +
    Did we forget about something? -

    +

    **Why would anyone participate in this system?** @@ -1356,9 +1357,9 @@ Why would anyone participate in this system? Why would anyone vote? Why would an Ghost Town -

    +

    No user wants to participate -

    +

    Getting information from the real world is an effort and they voters are doing the protocol a service
    @@ -1381,12 +1382,12 @@ We need a rewards scheme or otherwise the network will be a ghost town. Reward Scheme -

    +

    If users are doing the protocol a service they need to be rewarded -

    +

    One way to do it is to mint some token rewards for well-behaved voters
    -
    +
    Or distribute them from a previously acquired pool of rewards
    @@ -1421,12 +1422,12 @@ Low-stakes oracles don't need to have super aggressive incentives. Reward Scheme Question -

    +

    Can we distribute fixed value rewards for correct votes? -
    Correct vote = 10$ +
    Correct vote = 10$
    -

    +

    No. We should base rewards on the size of the voter's stake. @@ -1460,12 +1461,19 @@ So the reward should be proportional to the stake. **In summary:** - Make it easy to honest users and hard for attackers + + - Service to the protocol needs to be rewarded + + - Destructive or interfering actions need to be punished + + - De-Sybiling the users can help defend against spam + Notes: @@ -1526,11 +1534,11 @@ For them to work a bunch of code needs to be deployed on the chain. -
    +
    State Storage Replication -

    +

    Whenever we store something on chain (like a smart contract) it needs to be at least partially replicated among the nodes. -

    +

    Multiple nodes store the same data.
    @@ -1551,11 +1559,11 @@ Thousands of nodes store the same data which is not super efficient. -
    +
    State Storage Replication Costs -

    +

    Ethereum deals with the burden of replication by charging more gas for submitting bulky data. -

    +

    All of that is ON TOP OF any computation gas costs.
    @@ -1577,11 +1585,11 @@ And that's on top of any computation costs. -
    +
    State Storage Duration -

    +

    This particular part of the state might be relevant for future state transitions so nodes cannot simply discard it. -

    +

    Full nodes need to keep ALL the data.
    @@ -1605,12 +1613,12 @@ Now let's explore an example. -
    +
    Meet Bob -

    +

    Bob happily deploys his awesome smart contract in Ethereum. He paid a hefty gas fee but so be it. -

    +

    Deploying a smart contract on chain @@ -1632,11 +1640,11 @@ His code was added to the state and now many nodes hold a copy of it. -
    +
    The Problem -

    +

    Bob decided to become a musician or just no longer likes programming. -

    +

    He doesn't care about his smart contract anymore.
    @@ -1659,11 +1667,11 @@ His code still lives in the state and has to be continuously replicated and main -
    +
    The Problem Made Worse -

    +

    Many others like Bob follow suit. -

    +

    Some of them continue developing but, why bother removing old data? They already paid for it.
    @@ -1685,11 +1693,11 @@ And some of them just don't care anymore. -
    +
    "Why Bother?" -

    +

    Getting data on chain is expensive, but there is no incentive to clean it up. -

    +

    This is a core misalignment of incentives that lead to Ethereum state size growing out of control.
    @@ -1714,9 +1722,9 @@ So the chain was getting overwhelmed in junk. -
    +
    The Goal -

    +

    Design new protocol rules that shape the behavior of the users in a way that they start cleaning up the state.
    @@ -1737,11 +1745,11 @@ Hopefully without any side effects. -
    +
    The Solution -

    +

    State Storage Gas Refunds -

    +

    Pay a hefty fee when deploying data to state, but get some of it refunded when removing it.
    @@ -1761,7 +1769,7 @@ So now there is an incentive to clean up the state. #### _Ethereum State Storage Issue_ -

    +

    behavior Before Developer becoming a musician @@ -1776,7 +1784,7 @@ So what we had originally is Bob paid for his smart contract and then simply wen #### _Ethereum State Storage Issue_ -

    +

    behavior After Developer removing his contract and becoming a musician @@ -1821,11 +1829,11 @@ When choosing between 10 and 30$ the opportunity cost of picking 30 is 10, the o -
    +
    The Real Cost -

    +

    Instead of having the funds locked in the storage deposit/refund scheme, Bob could have invested them somewhere else and gain some profit. -

    +

    Just locking your funds is sort of a punishment by itself.
    @@ -1855,7 +1863,8 @@ The opportunity cost is a clever mechanism that allows us to include costs witho - Creating invalid blocks in Bitcoin never gets directly punished even if the block is rejected by the network. The real cost is the opportunity cost, as the miner could have mined a valid block instead. - Polkadot native token DOT is inflationary (\~7.5% per year) but it can be staked to earn rewards (~15% per year). -Not staking DOT has an opportunity cost which incentives staking to secure the network. + Not staking DOT has an opportunity cost which incentives staking to secure the network. + Notes: @@ -1920,9 +1929,9 @@ As protocol engineers or system designers you need to identify those externality -
    +
    Negative Externality Cost -

    +

    In the Ethereum State Storage problem we priced in the negative externality as the opportunity cost of locking your funds.
    @@ -1944,11 +1953,11 @@ We aligned his incentives with the incentives of the chain. -
    +
    Positive Externality -

    +

    Providing the voting services in the Oracle scheme can be seen as a positive externality for the network that can further use this extra information. -

    +

    The voters are providing a valuable service to the protocol.
    @@ -1989,11 +1998,11 @@ So having that mind should they pay any transaction fees when submitting votes? -
    +
    Beneficial Transactions -

    +

    Such a transaction can be totally free. -

    +

    But make sure it cannot be spammed!
    @@ -2017,9 +2026,9 @@ This way we remain safe and can make the transaction free to further incentivize -
    +
    There are other free transactions that are not necessarily positive externalities. -

    +

    Inherent Transactions
    • Block rewards in BTC
    • @@ -2084,9 +2093,9 @@ They as they name suggests validate if the new blocks in the network are valid a -
      +
      Approval Checkers -

      +

      In Polkadot when new blocks are validated, not everyone does the work. Only some randomly chosen validators - called Approval Checkers - are selected to validate candidate blocks.
      @@ -2109,11 +2118,11 @@ They are called Approval Checkers. -
      +
      Attackers -

      +

      We assume that attackers can DDoS some but not ALL Validators. -

      +

      Being DDoS'ed makes them unable to vote in time.
      @@ -2186,6 +2195,7 @@ And only eliminate the relevant targets thus compromising the network. - Limit the information the attackers have access to so they cannot plan ahead + Notes: @@ -2210,7 +2220,7 @@ We need to make this a game of incomplete information, where some things are hid - Approval Checkers reveal themselves by showing their low numbers and publish a vote at the same time - If all the votes received confirm the block is fine it passes -
      +
      Notes: @@ -2322,7 +2332,7 @@ Old incentives that were previously sensible may now motivate a vastly different Restaking through EigenLayer incentives Ethereum stakers to stake the same funds for multiple apps at the same time. -

      +

      The incentive game will be vastly different and the capital will effectively be leveraged (double risk and double rewards).
      @@ -2348,9 +2358,9 @@ This is not something natively available in Ethereum and it wasn't taken into co Consequences -

      +

      Restaking consequences are still not fully understood and the research is ongoing. -

      +

      Speaker Notes ("S") for further reading.
      @@ -2366,7 +2376,7 @@ The whole field of blockchain incentivization and protocol design is still devel Thats it... - Podcast: -- Whitepaper: +- Whitepaper: --- diff --git a/content/blockchain-contracts/finality/slides.md b/content/blockchain-contracts/finality/slides.md index e1c18df..8021478 100644 --- a/content/blockchain-contracts/finality/slides.md +++ b/content/blockchain-contracts/finality/slides.md @@ -20,7 +20,8 @@ Trust example: If everyone trusts each other, then any one person can propose an Social Hierarchy example: If a community has an executive (President, Queen, CEO), the executive can propose her preference and everyone will accept it based on the external mechanism that keeps her as the executive. -But these conditions are not interesting, and are often not realistic. It gets interesting when we don't make these simplifying assumption. +But these conditions are not interesting, and are often not realistic. +It gets interesting when we don't make these simplifying assumption. ---v @@ -113,7 +114,8 @@ Image source: @@ -232,8 +236,12 @@ Before I can tell you exactly how and where it can be solved, we have to underst A network is one of: - **Synchronous** - When sent, a message is received immediately by all. -- **Asynchronous** - When a message is sent it may be received after some delay, or not at all. The sender doe not know whether it is received. Messages may be received in different orders by different parties. -- **Partially Synchronous** - When a message is sent, it may be received after some delay up to a maximum delay, $T$. It may not be dropped entirely. Messages may be received in different orders by different parties. +- **Asynchronous** - When a message is sent it may be received after some delay, or not at all. + The sender doe not know whether it is received. + Messages may be received in different orders by different parties. +- **Partially Synchronous** - When a message is sent, it may be received after some delay up to a maximum delay, $T$. + It may not be dropped entirely. + Messages may be received in different orders by different parties. Roughly analogous to real-time (async) vs. turn-based (sync) games. @@ -255,10 +263,14 @@ Classify each of these: Notes: -- Telephone call is sync. You say something and wait for the other party to reply -- Mail is async. You send a letter, then go do other stuff for several days +- Telephone call is sync. + You say something and wait for the other party to reply +- Mail is async. + You send a letter, then go do other stuff for several days - Jitsi video call is basically sync just like the phone call. -- The others can be either. Sometimes you text back and forth quickly and wait for replies. Other times you send and come back later like mail. +- The others can be either. + Sometimes you text back and forth quickly and wait for replies. + Other times you send and come back later like mail. --- @@ -267,7 +279,7 @@ Notes: A system is one of: - **Deterministic** - The same inputs give the same outputs every time. -- **Probabilistic** - The same inputs may not give the same outputs.
      +- **Probabilistic** - The same inputs may not give the same outputs.
      $~~~~~~~~~~~~~~~~~~~~~~~~~$ Requires a source of entropy. eg coin flipping. --- @@ -280,7 +292,8 @@ A system is one of: Notes: -Once it was shown that deterministic consensus is impossible in an async network, the field split into two major parts. Either you: +Once it was shown that deterministic consensus is impossible in an async network, the field split into two major parts. +Either you: - Assume the network is (at least partially) synchronous - Introduce non-determinism @@ -294,11 +307,12 @@ One interesting thing about Nakamoto pow consensus is that it does _both_. ## Ongoing Consensus -We want to continue agreeing on
      an every-growing history of events +We want to continue agreeing on
      an every-growing history of events Notes: -Blockchains are intended to keep processing and finalizing transactions forever. This is more like deciding where to go to dinner every night over and over. +Blockchains are intended to keep processing and finalizing transactions forever. +This is more like deciding where to go to dinner every night over and over. ---v @@ -313,11 +327,16 @@ Blockchains are intended to keep processing and finalizing transactions forever. Notes: -Traditional literature typically uses the term safety. Blockchain folks typically talk about finality. They basically mean the same thing. +Traditional literature typically uses the term safety. +Blockchain folks typically talk about finality. +They basically mean the same thing. Finality can be proved to entities that are not involved in consensus. -We spoke about liveness previously in the authoring system. There it means that more blocks will be authored, more blockspace will be created and put up for sale. Here, in finality, it means that more blocks will be finalized. Of course liveness in the finality depends on liveness in the authoring. +We spoke about liveness previously in the authoring system. +There it means that more blocks will be authored, more blockspace will be created and put up for sale. +Here, in finality, it means that more blocks will be finalized. +Of course liveness in the finality depends on liveness in the authoring. These two decisions can be entirely orthogonal to one another, or wrapped up together. @@ -325,15 +344,18 @@ These two decisions can be entirely orthogonal to one another, or wrapped up tog ## Liveness vs Termination -Earlier I described Termination as desireable,
      now I'm saying Liveness is desireable. +Earlier I described Termination as desireable,
      now I'm saying Liveness is desireable. Are these at odds with each other? Notes: -Termination guarantees that, for a given decision, each honest participant will eventually decide something. This concept is relevant when there is a single decision to be made. In the blockchain context, it guarantees that we will eventually know which block is final at height n. +Termination guarantees that, for a given decision, each honest participant will eventually decide something. +This concept is relevant when there is a single decision to be made. +In the blockchain context, it guarantees that we will eventually know which block is final at height n. -Liveness guarantees that a system that is intended to continue making progress, will indeed eventually make progress. In the context of the blockchain, liveness means that once we've decided what block is final at height n, we will eventually go on to decide what block is final at height n + 1. +Liveness guarantees that a system that is intended to continue making progress, will indeed eventually make progress. +In the context of the blockchain, liveness means that once we've decided what block is final at height n, we will eventually go on to decide what block is final at height n + 1. --- @@ -343,17 +365,18 @@ Liveness guarantees that a system that is intended to continue making progress, - Longest chain rule - Longest chain is "best"... for now -- Someone could always start mining a chain
      and,with low but non-zero probability,
      end up with it longer. -- There could _already_ be a longer chain
      that you just haven't heard of. +- Someone could always start mining a chain
      and,with low but non-zero probability,
      end up with it longer. +- There could _already_ be a longer chain
      that you just haven't heard of. -The finality is only probabilistic.
      +The finality is only probabilistic.
      Nakamoto consensus in only safe in a synchronous network. Notes: -This is to say that Nakamoto consensus is NOT safe on the real asynchronous internet. In practice, as long as +This is to say that Nakamoto consensus is NOT safe on the real asynchronous internet. +In practice, as long as blocks can be downloaded and executed much more quickly than the target block time, it is usually good enough. - Longest could also mean most accumulated work @@ -381,13 +404,15 @@ blocks can be downloaded and executed much more quickly than the target block ti Notes: -If you want deterministic finality, it basically means employing BFT agreement protocols that we talked about in the history lesson. This means we need a finite authority set with an honest majority. And that means we need incentives to keep them honest. +If you want deterministic finality, it basically means employing BFT agreement protocols that we talked about in the history lesson. +This means we need a finite authority set with an honest majority. +And that means we need incentives to keep them honest. ---v ## Incentives: Game Theory! -Abstractly: You behave honestly
      when the utility of doing so exceeds the cost. +Abstractly: You behave honestly
      when the utility of doing so exceeds the cost. Incentive designers may potentially: @@ -400,9 +425,11 @@ Incentive designers may potentially: Notes: -Many systems use both of these, but doing so is not strictly necessary. Even without slashes, the opportunity cost of staking and the missed rewards from authoring invalid blocks may be sufficient. +Many systems use both of these, but doing so is not strictly necessary. +Even without slashes, the opportunity cost of staking and the missed rewards from authoring invalid blocks may be sufficient. -It is often the case that blockchain systems give rewards in the authorship and punishments in the finality. There is no fundamental reason for this; it is just a little more straightforward to implement. +It is often the case that blockchain systems give rewards in the authorship and punishments in the finality. +There is no fundamental reason for this; it is just a little more straightforward to implement. ---v @@ -413,15 +440,16 @@ It is often the case that blockchain systems give rewards in the authorship and - Authoring when you aren't supposed to - Failing to author when you are supposed to - Casting finality votes for conflicting blocks -- Casting a finality vote for a block (or chain)
      that includes an invalid state transition. +- Casting a finality vote for a block (or chain)
      that includes an invalid state transition. -> How severe are each of these offenses?
      -> Do they all warrant a slash?
      +> How severe are each of these offenses?
      +> Do they all warrant a slash?
      > A full slash? Notes: -PoW has inherent punishment through wasted energy. BFT based system's don't. +PoW has inherent punishment through wasted energy. +BFT based system's don't. Instead, aspiring participants will typically lock up a security deposit which can be slashed in part or in whole. @@ -429,11 +457,11 @@ Instead, aspiring participants will typically lock up a security deposit which c ### Concrete Punishment Example -Let's say a slash is 100 units, and the reporter gets 10%.
      I plan to attack. +Let's say a slash is 100 units, and the reporter gets 10%.
      I plan to attack. -If my attack is successful,
      I expect to gain roughly 200 units worth of utility. +If my attack is successful,
      I expect to gain roughly 200 units worth of utility. -I ask another authority to cooperate with me:
      "I'll pay you 20 units to _not_ rat me out for my attack". +I ask another authority to cooperate with me:
      "I'll pay you 20 units to _not_ rat me out for my attack". > How would you respond? @@ -449,18 +477,22 @@ Notes: - Authorship is like Aura - simple round robin - Naive but **simple** BFT implementation -- If the block has enough votes
      by the end of the slot, it is finalized.
      +- If the block has enough votes
      by the end of the slot, it is finalized.
      Otherwise, it is rejected via timeout. - "Instant finality" -- Forkless - Forks are disallowed
      because blocks can only be authored
      on finalized parents. +- Forkless - Forks are disallowed
      because blocks can only be authored
      on finalized parents.
      Notes: -Tendermint assumes a partially synchronous network, like all the BFT based systems - That is to say that messages may not arrive immediately, but will arrive within a finite time bound. In practice this means it is slot-based just like so many of the authoring schemes. +Tendermint assumes a partially synchronous network, like all the BFT based systems - That is to say that messages may not arrive immediately, but will arrive within a finite time bound. +In practice this means it is slot-based just like so many of the authoring schemes. -Tendermint is often touted as "instant finality". It is instant in the sense that finality is tied to authorship. In practice this means that authorship, which is inherently O(n), is slowed down to stay in sync with finality which is O(n^2). They sacrifice liveness to guarantee absolute safety at all times. +Tendermint is often touted as "instant finality". +It is instant in the sense that finality is tied to authorship. +In practice this means that authorship, which is inherently O(n), is slowed down to stay in sync with finality which is O(n^2). +They sacrifice liveness to guarantee absolute safety at all times. ---v @@ -520,7 +552,7 @@ Tendermint is often touted as "instant finality". It is instant in the sense tha ## What About Re-Orgs -
      +
      Notes: @@ -532,13 +564,14 @@ Previously we talked about how a node's view of the best block can change, and t ## Modified Fork Choice Rule -
      +
      Only extend best finalized chain Notes: -Once you have a finality gadget installed, you have to make sure you only ever author on top of finalized blocks. Even if another chain is longer. +Once you have a finality gadget installed, you have to make sure you only ever author on top of finalized blocks. +Even if another chain is longer. --- @@ -547,7 +580,7 @@ Once you have a finality gadget installed, you have to make sure you only ever a - Deterministic finality _only_ -- Requires an external block authoring scheme
      with its own liveness proof. +- Requires an external block authoring scheme
      with its own liveness proof. - Kind of like Tendermint but better. - Finalizes chains, not blocks. @@ -774,7 +807,7 @@ Notes: - Consensus systems can be {Deterministic, Probabilistic} - Consensus systems can be {Open participation, Finite participation} - There is always an assumption that at least {1/2, 2/3} participants are honest -- In decentralized systems, we use Economics and Game Theory
      to incentivize honest execution of the consensus protocol +- In decentralized systems, we use Economics and Game Theory
      to incentivize honest execution of the consensus protocol --- @@ -782,4 +815,4 @@ Notes: # Game Time -> I want to play a game...
      a board game! +> I want to play a game...
      a board game! diff --git a/content/blockchain-contracts/forks/slides.md b/content/blockchain-contracts/forks/slides.md index 5718f72..d7410c7 100644 --- a/content/blockchain-contracts/forks/slides.md +++ b/content/blockchain-contracts/forks/slides.md @@ -17,7 +17,7 @@ duration: 60 minutes #### Ideal World In an ideal world blockchains would look like this: -

      +

      @@ -29,7 +29,7 @@ In an ideal world blockchains would look like this: Things don't always go according to plan: -
      +
      @@ -41,7 +41,7 @@ Things don't always go according to plan: And sometimes they get extra messy: -
      +
      @@ -86,9 +86,9 @@ It will cover most of the common terms and hopefully will not be as self-contrad #### _Fork Confusion_ -
      +
      BABE (sometimes): -

      +

      Notes: @@ -108,7 +108,7 @@ Some of you might have heard about soft forks and hard forks, any idea which one #### _Forks Family Tree_ -
      +
      Notes: @@ -131,7 +131,7 @@ For that we'll talk about transitory forks. #### _Transitory Forks_ -
      +
      Notes: @@ -143,7 +143,7 @@ They are often also called short-lived forks or temporary forks. ## Transitory Forks -
      +
      Notes: @@ -169,7 +169,7 @@ Consensus forks. #### _Consensus Forks_ -
      +
      Notes: @@ -193,7 +193,7 @@ But first before we understand the intricacies of consensus forks we need to und #### _Validity Set_ -
      +
      Notes: @@ -203,7 +203,7 @@ You don't need to understand all the fields that are in it but for now take a lo #### _Validity Set_ -
      +
      ---v @@ -212,7 +212,7 @@ You don't need to understand all the fields that are in it but for now take a lo #### _Validity Set_ -
      +
      ---v @@ -221,7 +221,7 @@ You don't need to understand all the fields that are in it but for now take a lo #### _Validity Set_ -
      +
      Notes: @@ -237,7 +237,7 @@ So if there is a block D that for instance is too big, it's blocksize is bigger #### _Validity Set_ -
      +
      Notes: @@ -251,7 +251,7 @@ Only some of those data blobs are valid blocks. #### _Validity Set_ -
      +
      Notes: @@ -269,7 +269,7 @@ They only like when it's even so they band together and change the protocol to o #### _Validity Set_ -
      +
      Notes: @@ -314,7 +314,7 @@ To understand the example from a second ago we'll dive into soft forks. #### _Soft Forks_ -
      +
      Notes: @@ -363,7 +363,7 @@ Before we jump into demonstration is decreasing or increasing blocksize a soft f
      Examples: -

      +

      • Decreasing blocksize
      • Accepting only even/odd hashes
      • @@ -444,7 +444,7 @@ Hidden forks. #### _Hidden Forks_ -
        +
        Notes: @@ -495,7 +495,7 @@ TL;DR the stuff we removed from the validity set wasn't even used despite being Examples: -

        +

        • Assigning non-conflicting uses to empty opcodes.
        • BTC Ordinals using empty opcodes to implement BTC NFTs.
        • @@ -540,7 +540,7 @@ Notes: #### _Hard Forks_ -
          +
          ---v @@ -577,7 +577,7 @@ Notes: Examples: -

          +

          • Increasing blocksize
          • BTC Cash fork at first*
          • @@ -639,12 +639,12 @@ So if there is a major change that most people accept but not everyone it will a -
            +
            -
            +
            @@ -668,7 +668,7 @@ We only have permanent forks in soft forks with under 50% support and in hard fo #### _Full Forks_ -
            +
            ---v @@ -705,7 +705,7 @@ We only have permanent forks in soft forks with under 50% support and in hard fo Examples: -

            +

            • Changing the hashing function
            • Changing the signature scheme
            • @@ -738,12 +738,12 @@ We only have permanent forks in soft forks with under 50% support and in hard fo -
              +
              -
              +
              @@ -757,7 +757,8 @@ Notes: - Soft are often preferred for changes because with >50%HP they do not fracture the community (BTC community logic) - Hard can be preferred as they seem to better represent minorities. If some people don't agree with the majority they naturally fork off and are not peer pressured to follow (ETH community logic) -- *** + +--- # Thank you! diff --git a/content/blockchain-contracts/infrastructure/slides.md b/content/blockchain-contracts/infrastructure/slides.md index ae74c96..895fa0b 100644 --- a/content/blockchain-contracts/infrastructure/slides.md +++ b/content/blockchain-contracts/infrastructure/slides.md @@ -53,7 +53,8 @@ Notes: We know we need somewhere to run these things with no back door or trusted party. -We have seen some hints so far. Let's check them out. +We have seen some hints so far. +Let's check them out. ---v @@ -66,7 +67,8 @@ We have seen some hints so far. Let's check them out. Notes: -Web2 gets a lot of this right. At least they are good at the first two and preventing accidental data loss etc. +Web2 gets a lot of this right. +At least they are good at the first two and preventing accidental data loss etc. There is a lot to be kept from web 2. Some digital services, or subsystems of digital services may never even need web3 upgrades. diff --git a/content/blockchain-contracts/ink-workshop/slides.md b/content/blockchain-contracts/ink-workshop/slides.md index 56d7d45..d7df58b 100644 --- a/content/blockchain-contracts/ink-workshop/slides.md +++ b/content/blockchain-contracts/ink-workshop/slides.md @@ -8,7 +8,9 @@ duration: 20 min Notes: -This workshop was an idea that came from first wave of PBA in Cambridge. The first time it was ever played was back in Buenos Aires. It's very much a PBA right of passage, so it's exciting to be able to play today. +This workshop was an idea that came from first wave of PBA in Cambridge. +The first time it was ever played was back in Buenos Aires. +It's very much a PBA right of passage, so it's exciting to be able to play today. --- @@ -26,7 +28,7 @@ This is us playing in BA earlier this year. ## Components -
              +
              @@ -56,10 +58,16 @@ This is us playing in BA earlier this year. Notes: -The game has three components: -**click** the first is a game contract, which is something that we have taken care of. I will deploy it and run it on Rococo. The game contract runs the game loop. It invokes each player contract and it determines the score. -**click** And the player.contract, that's your job. so we we have a template for a very basic player and you can basically modify it in any way you like. I will explain the scoring function in a moment. -**click** Lastly, we have a front-end that we will put on the big screen here, but it's online, you can open it up on your laptop and follow the game locally. +The game has three components: + +- **click** the first is a game contract, which is something that we have taken care of. + I will deploy it and run it on Rococo. + The game contract runs the game loop. + It invokes each player contract and it determines the score. +- **click** And the player.contract, that's your job. + so we we have a template for a very basic player and you can basically modify it in any way you like. + I will explain the scoring function in a moment. +- **click** Lastly, we have a front-end that we will put on the big screen here, but it's online, you can open it up on your laptop and follow the game locally. --- @@ -73,13 +81,22 @@ The game has three components: Notes: -So the process is as follows: -**click** - you brainstorm and create a contract that plays on your behalf ideally in a better way than the other contracts -**click** - you deploy the contract to the Rococo testnet -**click** - you register your contract as a player with the game contract. We will publish the addresses and it's it's not complicated you can just use contracts UI. I will also show it in a second -**click** - then we start the game. We have a script that calls the game contract regularly and the front end will display the changes -**click** - so the game will run for some minutes. Your contract will already be uploaded at this point - so you can't do anything. The contract will play on your behalf. Meaning it's hands off. I mean you can also change it with upgradable contract patterns and stuff, but in general, you won't have to. So you can just watch the game play out. -If you're familiar with AI agents, that's also a similar idea, where you have an agent that plays a game on your behalf. +So the process is as follows: + +- **click** - you brainstorm and create a contract that plays on your behalf ideally in a better way than the other contracts +- **click** - you deploy the contract to the Rococo testnet +- **click** - you register your contract as a player with the game contract. + We will publish the addresses and it's it's not complicated you can just use contracts UI. + I will also show it in a second +- **click** - then we start the game. + We have a script that calls the game contract regularly and the front end will display the changes +- **click** - so the game will run for some minutes. + Your contract will already be uploaded at this point - so you can't do anything. + The contract will play on your behalf. + Meaning it's hands off. + I mean you can also change it with upgradable contract patterns and stuff, but in general, you won't have to. + So you can just watch the game play out. + If you're familiar with AI agents, that's also a similar idea, where you have an agent that plays a game on your behalf. --- @@ -100,8 +117,10 @@ You can see, it's a it's a coordinate grid. Notes: -this is X1 y0 -And the idea is for you, as a contract developer, to paint as many fields of this canvas of the script as possible. There's an API function for how to paint. I'll show it in a minute, but the idea is that in the end the contract that painted the most Fields wins. +this is X1 y0. +And the idea is for you, as a contract developer, to paint as many fields of this canvas of the script as possible. +There's an API function for how to paint. +I'll show it in a minute, but the idea is that in the end the contract that painted the most Fields wins. --- @@ -111,7 +130,9 @@ And the idea is for you, as a contract developer, to paint as many fields of thi Notes: -So yeah, there's bit of scoring to be done. There's also scoreboard here on the side, where all players will be shown as well as their rank. You will be assigned a random color to your player contract. +So yeah, there's bit of scoring to be done. +There's also scoreboard here on the side, where all players will be shown as well as their rank. +You will be assigned a random color to your player contract. --- @@ -135,11 +156,20 @@ So yeah, there's bit of scoring to be done. There's also scoreboard here on the Notes: -This game was designed in a way where all of the best practices for smart contract development will make your player run better. We really tried to gamify some of the concepts that are really best practices of how you should develop a smart contract. -**click** - first one is to use as little gas as possible to paint as many fields as possible. Gas consumption is a super big thing as user fees derived from that and the transaction throughput also relates to how big a contract is so the less complex your contract is the better it will do. -**click** - There's a certain gas budget allocated per player and if you if you're above that then you just won't make a turn. So you have to stay in an optimal gas budget. -**click** - the later in the in the game that you still manage to paint the field the better you score because what will happen is that there will be all kinds of fields painted and it will convert to a place where there's only a few left. so if you have a player that just randomly tries to paint things then at some at some point it just won't no longer work because it doesn't paint the unpainted fields. But in order to find those, you will have to have some more complex logic in your contract. -**click** - and lastly, there's no overpainting. So the first player to paint a field owns it. So if you have a contract that just paints the same field over and over again, it will just not work. So you have to have some logic in there that checks whether a field is already painted or not. +This game was designed in a way where all of the best practices for smart contract development will make your player run better. +We really tried to gamify some of the concepts that are really best practices of how you should develop a smart contract. + +- **click** - first one is to use as little gas as possible to paint as many fields as possible. + Gas consumption is a super big thing as user fees derived from that and the transaction throughput also relates to how big a contract is so the less complex your contract is the better it will do. +- **click** - There's a certain gas budget allocated per player and if you if you're above that then you just won't make a turn. + So you have to stay in an optimal gas budget. +- **click** - the later in the in the game that you still manage to paint the field the better you score because what will happen is that there will be all kinds of fields painted and it will convert to a place where there's only a few left. + so if you have a player that just randomly tries to paint things then at some at some point it just won't no longer work because it doesn't paint the unpainted fields. + But in order to find those, you will have to have some more complex logic in your contract. +- **click** - and lastly, there's no overpainting. + So the first player to paint a field owns it. + So if you have a contract that just paints the same field over and over again, it will just not work. + So you have to have some logic in there that checks whether a field is already painted or not. --- @@ -169,17 +199,24 @@ mod player { Notes: -So this is a very basic player contract. -We have a repository app set up with the template for this - I will share the link in a second. How it looks is - it's a contract that defines the player module, -**click** - a super simple player doesn't have to contain any storage whatsoever. -**click**- a super simple player also doesn't have to contain any Constructor arguments -**click** - and it can just return a random constant value. So this is the most simple player ever. -What your player needs to do is to have one message, that has a defined selector, so you don't have to think more about this. It's just that it needs to have this function and this function is called by the game with every round. And whatever you return from this function. This is your your turn for the game. -So if in this case you return an option some(1,2), this would mean you paint the pixel at X1 Y2. -In that case, it would be a very boring play. -Who can tell me what would happen here? -_(a player that only makes one turn - it always tries to paint the same field. And if someone else also chose the same magic numbers then it wouldn't even make a turn at all.)_ -**click** - So there's a couple things of how you can improve on that and I will show some hints later, but for now what we're gonna do is look at the repository and see how we can get started with this. +So this is a very basic player contract. +We have a repository app set up with the template for this - I will share the link in a second. +How it looks is - it's a contract that defines the player module. + +- **click** - a super simple player doesn't have to contain any storage whatsoever. +- **click**- a super simple player also doesn't have to contain any Constructor arguments +- **click** - and it can just return a random constant value. + So this is the most simple player ever. + What your player needs to do is to have one message, that has a defined selector, so you don't have to think more about this. + It's just that it needs to have this function and this function is called by the game with every round. + And whatever you return from this function. + This is your your turn for the game. + So if in this case you return an option some(1,2), this would mean you paint the pixel at X1 Y2. + In that case, it would be a very boring play. + Who can tell me what would happen here? + _(a player that only makes one turn - it always tries to paint the same field_. + _And if someone else also chose the same magic numbers then it wouldn't even make a turn at all_.) +- **click** - So there's a couple things of how you can improve on that and I will show some hints later, but for now what we're gonna do is look at the repository and see how we can get started with this. --- @@ -208,7 +245,9 @@ It contains the cargo.toml file and the lib.rs, which is the player that I just Notes: -It contains the game metadata. You will need this in order to interact with the game itself, to register your player and so on. but yeah we will show that. +It contains the game metadata. +You will need this in order to interact with the game itself, to register your player and so on. +but yeah we will show that. --- @@ -229,8 +268,9 @@ The first is some instructions on General setup and the second one is in order t Notes: -So, the first thing that we are going to do is that I would ask all of you to go to this link here and follow the instructions. -We will go around and help whoever has an issue. I think you might even have already used some of the requirements in there, so it may not be super complicated. +So, the first thing that we are going to do is that I would ask all of you to go to this link here and follow the instructions. +We will go around and help whoever has an issue. +I think you might even have already used some of the requirements in there, so it may not be super complicated. --- @@ -240,7 +280,8 @@ We will go around and help whoever has an issue. I think you might even have alr Notes: -For this stage, you will need the address of the game. We'll post it in the chat. +For this stage, you will need the address of the game. +We'll post it in the chat. This is a simple example - we're just giving you exposure to the flow of uploading your player contract. --- @@ -251,7 +292,8 @@ This is a simple example - we're just giving you exposure to the flow of uploadi Notes: -The next slides go over strategy. (maybe wait to to go through until you've played one game) +The next slides go over strategy. +(maybe wait to to go through until you've played one game) --- @@ -277,21 +319,24 @@ The next slides go over strategy. (maybe wait to to go through until you've play Notes: -When you deployed it you already saw that there's different functions that you can call. -There are a lot of functions that are ineresting. -**click** - the game runner calls this - if you're interested, you can take a look how it works and there might be some hints for for the game. -**click** - then there's a function to to query the board in order to find out if certain fields are already occupied or if they are still free. -**click** - there's a function for the gas budget so you can find out how much gas your player is allowed to use per one round. Because worst thing is if you are above this gas budget, then you just won't execute any turn during that round. -**click** - there's also function to query the game dimensions. same thing there, if you paint outside the bounds, then also you just missed one turn. +When you deployed it you already saw that there's different functions that you can call. +There are a lot of functions that are interesting. + +- **click** - the game runner calls this - if you're interested, you can take a look how it works and there might be some hints for for the game. +- **click** - then there's a function to to query the board in order to find out if certain fields are already occupied or if they are still free. +- **click** - there's a function for the gas budget so you can find out how much gas your player is allowed to use per one round. + Because worst thing is if you are above this gas budget, then you just won't execute any turn during that round. +- **click** - there's also function to query the game dimensions. + Same thing there, if you paint outside the bounds, then also you just missed one turn. --- ## Things to consider 🧠 -- Develop a strategy for your player.

              +- Develop a strategy for your player.

              - Use as little gas as possible to paint as many fields as possible. - Stay within your gas budget. -- The later you manage to still paint a field, the better you score.

              +- The later you manage to still paint a field, the better you score.

              - No overpainting! First player to paint a field owns it. - [paritytech/squink-splash-advanced](https://github.com/paritytech/squink-splash-advanced) @@ -303,7 +348,9 @@ There are a lot of functions that are ineresting. Notes: -There's details in here. You could deploy locally to test things out. there's also commands you can use to deploy not using the UI. +There's details in here. +You could deploy locally to test things out. +there's also commands you can use to deploy not using the UI. --- @@ -332,9 +379,14 @@ There's details in here. You could deploy locally to test things out. there's al Notes: -**click** Lastly, some ideas for for your agent in the game you can you yourself can call your contract. as often as you want and this won't contribute to the gas used during the game. You can during the game you could also call a set of function of your contract if you want to adapt something. -**click** You could also Generate random numbers. There are a couple of libraries out there, if you want to go along those lines you have to pay attention that it's a no standard Library. typically a random number generator libraries they typically have a feature that you need to enable in order to make them no standard compatible -**click** A clever strategy would be a query which fields are free. that's a bit more complex with the with the code snippet that we have in this Advanced repository, this would give you a hint. +- **click** Lastly, some ideas for for your agent in the game you can you yourself can call your contract. + As often as you want and this won't contribute to the gas used during the game. + You can during the game you could also call a set of function of your contract if you want to adapt something. +- **click** You could also Generate random numbers. + There are a couple of libraries out there, if you want to go along those lines you have to pay attention that it's a no standard Library. + typically a random number generator libraries they typically have a feature that you need to enable in order to make them no standard compatible +- **click** A clever strategy would be a query which fields are free. + that's a bit more complex with the with the code snippet that we have in this Advanced repository, this would give you a hint. --- @@ -374,17 +426,17 @@ Solutions Explainer -
              +
              -Use as little gas as possible to paint as many fields as possible.

              -Stay within your gas budget.

              -The later you manage to still paint a field, the better you score.

              -No overpainting! First player to paint a field owns it.
              +Use as little gas as possible to paint as many fields as possible.

              +Stay within your gas budget.

              +The later you manage to still paint a field, the better you score.

              +No overpainting! First player to paint a field owns it.
              -
              -
              +
              +
              [paritytech/squink-splash-advanced](https://github.com/paritytech/squink-splash-advanced) @@ -415,14 +467,14 @@ No overpainting! First player to paint a field owns it.
              ## Board Dimensions - Worst 😱 - - Cross-contract call to `game`

              + - Cross-contract call to `game`

              ```rust #[ink(message)] pub fn dimensions(&self) -> (u32, u32) ``` -

              +

              @@ -482,34 +534,43 @@ fn pay_winner( --- -## Strategy 1
              Return Random Numbers +## Strategy 1
              Return Random Numbers --- -## Strategy 1
              Return Random Number +## Strategy 1
              Return Random Number - Wasm-compatible RNG + + - Use Storage to hold seed for random number + + - 📈 Uses little Gas + + - 📉 Quickly runs into collisions + + - 📉 Score function rewards players that late in game still paint fields + --- -## Strategy 2
              Paint only free fields +## Strategy 2
              Paint only free fields --- -## Strategy 2
              Paint only free fields +## Strategy 2
              Paint only free fields - Query board for free fields - 📈 Succeeds late in game @@ -523,16 +584,16 @@ fn pay_winner( --- -## Strategy 3
              Shift computation off-chain +## Strategy 3
              Shift computation off-chain --- -## Strategy 3
              Shift computation off-chain +## Strategy 3
              Shift computation off-chain - Off-chain Script - - Query board ➜ Search free field

              + - Query board ➜ Search free field

              @@ -550,18 +611,20 @@ fn pay_winner( --- -## Strategy 4
              Exploit player sorting in game loop +## Strategy 4
              Exploit player sorting in game loop --- -## Strategy 4
              Exploit player sorting in game loop +## Strategy 4
              Exploit player sorting in game loop - On top of Strategy 3 (off-chain computation). + - Game loop calls players in same order each time. + ```rust @@ -581,7 +644,7 @@ fn submit_turn(&mut self) { --- -## Strategy 4
              Exploit player sorting in game loop +## Strategy 4
              Exploit player sorting in game loop ```rust impl AddressGenerator for DefaultAddressGenerator { @@ -608,7 +671,7 @@ impl AddressGenerator for DefaultAddressGenerator { --- -## Strategy 5
              Checking these slides already yesterday +## Strategy 5
              Checking these slides already yesterday diff --git a/content/blockchain-contracts/ink/slides.md b/content/blockchain-contracts/ink/slides.md index b4dcade..3b9f9e8 100644 --- a/content/blockchain-contracts/ink/slides.md +++ b/content/blockchain-contracts/ink/slides.md @@ -179,9 +179,9 @@ path = "lib.rs" [features] default = ["std"] std = [ - "ink/std", - "scale/std", - "scale-info/std", + "ink/std", + "scale/std", + "scale-info/std", ] ``` @@ -259,7 +259,8 @@ Artifacts: The contract was built in RELEASE mode. -Your contract artifacts are ready. You can find them in: +Your contract artifacts are ready. +You can find them in: /home/CloudStation/Blockchain-Academy/flipper/target/ink - flipper.contract (code + metadata) @@ -479,6 +480,7 @@ pub fn get(&self) -> bool { - `#[ink(message)]` is how we tell ink! this is a function that can be called on the contract - `&self` is a reference to the contract's storage + Notes: @@ -538,7 +540,6 @@ pub fn spin(&mut self) -> Result<()> { }; pub type Result = core::result::Result; - ```
              @@ -568,7 +569,6 @@ pub fn flip(&mut self) { } } - ``` - what is the state of this contract if the tx is called in an odd block number? @@ -624,7 +624,6 @@ pub fn flip(&mut self) { } } - ``` - What happens to the events from reverted transactions? @@ -726,8 +725,8 @@ Notes: | Unsigned int | 42 | 0x2a00 | | | Enum | enum IntOrBool { Int(u8), Bool(bool)} | 0x002a and 0x0101 | first byte encodes the variant index, remaining bytes encode the data | | Tuple | (3, false) | 0x0c00 | concatenation of each encoded value | -| Vector | [4, 8, 15, 16, 23, 42] | 0x18040008000f00100017002a00 | encoding of the vector length followed by conatenation of each item's encoding | -| Struct | {x:30u64, y:true} | [0x1e,0x0,0x0,0x0,0x1] | names are ignored, Vec structure, only order matters | +| Vector | \[4, 8, 15, 16, 23, 42\] | 0x18040008000f00100017002a00 | encoding of the vector length followed by conatenation of each item's encoding | +| Struct | {x:30u64, y:true} | \[0x1e,0x0,0x0,0x0,0x1\] | names are ignored, Vec structure, only order matters |
              @@ -788,27 +787,27 @@ pub struct Flipper> {
              ```json - "storage": { - "root": { - "layout": { - "struct": { - "fields": [ - { - "layout": { - "leaf": { - "key": "0xcafebabe", - "ty": 0 - } - }, - "name": "value" - } - ], - "name": "Flipper" - } - }, - "root_key": "0xcafebabe" - } +"storage": { + "root": { + "layout": { + "struct": { + "fields": [ + { + "layout": { + "leaf": { + "key": "0xcafebabe", + "ty": 0 + } + }, + "name": "value" + } + ], + "name": "Flipper" + } + }, + "root_key": "0xcafebabe" } +} ```
              @@ -857,8 +856,6 @@ pub fn transfer(&mut self) { balance += endowment; } - - ``` - what is wrong here? @@ -866,7 +863,10 @@ pub fn transfer(&mut self) { Notes: - working with mapping: -- Answer: Mapping::get() method will result in an owned value (a local copy), as opposed to a direct reference into the storage. Changes to this value won't be reflected in the contract's storage "automatically". To avoid this common pitfall, the value must be inserted again at the same key after it was modified. The transfer function from above example illustrates this: +- Answer: Mapping::get() method will result in an owned value (a local copy), as opposed to a direct reference into the storage. + Changes to this value won't be reflected in the contract's storage "automatically". + To avoid this common pitfall, the value must be inserted again at the same key after it was modified. + The transfer function from above example illustrates this: --- @@ -941,7 +941,6 @@ pub fn set_code(&mut self, code_hash: [u8; 32]) -> Result<()> { ink::env::set_code_hash(&code_hash)?; Ok(()) } - ``` - Within SC's lifecycle it is often necessary to perform an upgrade or a bugfix. @@ -967,7 +966,6 @@ pub fn set_code(&mut self, code_hash: [u8; 32]) -> Result<()> { ink::env::set_code_hash(&code_hash)?; Ok(()) } - ``` Notes: @@ -1154,7 +1152,6 @@ Notes:
              ```rust [3-7,12,18] - #[ink(message)] pub fn swap( &mut self, @@ -1272,7 +1269,7 @@ impl MyContract { ## Blockchain node onion -
              +
              @@ -1337,7 +1334,7 @@ impl MyContract { ## Interacting with the state transition function -
              +
              @@ -1368,7 +1365,7 @@ impl MyContract { ## Interacting with the state transition function -
              +
              @@ -1397,7 +1394,7 @@ impl MyContract {
            • outsourcing computation
            • ...
            • -
              +
              **_chain extension_** @@ -1409,7 +1406,7 @@ impl MyContract { ## Runtime -
              +
              In Polkadot ecosystem _state transition function_ is called **_runtime_** @@ -1417,7 +1414,7 @@ In Polkadot ecosystem _state transition function_ is called **_runtime_** ## Calling runtime -
              +
              ```rust [7-10] #[ink(message)] @@ -1439,7 +1436,7 @@ pub fn transfer_through_runtime( ## Calling runtime -
              +
              ```rust [12] #[ink(message)] @@ -1461,7 +1458,7 @@ pub fn transfer_through_runtime( ## Chain extensions -
              +
              Chain extension is a way to extend the runtime with custom functionalities _dedicated to contracts_. @@ -1469,14 +1466,14 @@ Chain extension is a way to extend the runtime with custom functionalities _dedi ## Chain extensions -
              +
              **ink! side:** - provide `ChainExtension` trait - include extension in the `Environment` trait instantiation -
              +
              **runtime side:** @@ -1543,7 +1540,7 @@ impl ink::env::chain_extension::FromStatusCode for OutsourcingErr { ## Include extension in the `Environment` trait instantiation -
              +
              ```rust pub enum EnvironmentWithOutsourcing {} @@ -1562,7 +1559,7 @@ mod my_contract { ## Include extension in the `Environment` trait instantiation -
              +
              ```rust #[ink::contract(env = crate::EnvironmentWithOutsourcing)] @@ -1577,7 +1574,7 @@ mod my_contract { ## Handling extension calls -
              +
              ```rust [5-11] pub struct HeavyCryptoOutsourcingExtension; @@ -1609,7 +1606,7 @@ impl ChainExtension for HeavyCryptoOutsourcingExtension { ## Testing contracts -
              +
              @@ -1623,7 +1620,7 @@ impl ChainExtension for HeavyCryptoOutsourcingExtension { ## Unit tests -
              +
              ```rust [1-3] #[ink::test] @@ -1654,7 +1651,7 @@ fn erc20_transfer_works() { ## Unit tests -
              +
              ```rust [5-9] #[ink::test] @@ -1685,7 +1682,7 @@ fn erc20_transfer_works() { ## Unit tests -
              +
              ```rust [11-22] #[ink::test] @@ -1716,7 +1713,7 @@ fn erc20_transfer_works() { ## E2E tests -
              +
              ```rust [1-7] #[ink_e2e::test] @@ -1740,7 +1737,7 @@ async fn e2e_transfer(mut client: ink_e2e::Client) -> E2EResult<()> { ## E2E tests -
              +
              ```rust [9-13] #[ink_e2e::test] @@ -1764,7 +1761,7 @@ async fn e2e_transfer(mut client: ink_e2e::Client) -> E2EResult<()> { ## E2E tests -
              +
              ```rust [14] #[ink_e2e::test] @@ -1820,7 +1817,7 @@ async fn e2e_transfer(mut client: ink_e2e::Client) -> E2EResult<()> { ## Test core -
              +
              1. Preparing and encoding transaction data (_given_) 1. Transaction execution (_when_) @@ -1830,7 +1827,7 @@ async fn e2e_transfer(mut client: ink_e2e::Client) -> E2EResult<()> { ## quasi-E2E tests -
              +
              Interact directly with runtime, skipping node layer. @@ -1838,7 +1835,7 @@ Interact directly with runtime, skipping node layer. ## quasi-E2E tests -
              +
              ```rust #[test] diff --git a/content/blockchain-contracts/languages/slides.md b/content/blockchain-contracts/languages/slides.md index d78da96..ec94836 100644 --- a/content/blockchain-contracts/languages/slides.md +++ b/content/blockchain-contracts/languages/slides.md @@ -804,7 +804,6 @@ def referenceTypes(): map[0] = 0 map[1] = 10 map[2] = 20 - ``` ---v diff --git a/content/blockchain-contracts/light-clients-bridges/slides.md b/content/blockchain-contracts/light-clients-bridges/slides.md index 0506191..4ecbb69 100644 --- a/content/blockchain-contracts/light-clients-bridges/slides.md +++ b/content/blockchain-contracts/light-clients-bridges/slides.md @@ -43,6 +43,7 @@ Reality: - It takes a lot of disk, memory, etc - It takes some know-how - I don't need it _all the time_ +
              @@ -70,7 +71,7 @@ AKA, trust somebody else's node.
              • 🕵️ Spy on you (like infura).
              • - +
              • 🔞 Censor you
              • 🤥 Lie to you
              • 💔 Steal your boyfriend @@ -254,7 +255,7 @@ More on this after we cover the basic design. ### Trust-based -Trusted intermediary makes a transfer manually.
                +Trusted intermediary makes a transfer manually.
                Eg. Wrapped bitcoin on ethereum (WBTC) @@ -262,7 +263,7 @@ Eg. Wrapped bitcoin on ethereum (WBTC) ### Trustless -Trustless is the goal,
                like almost everything in web3. +Trustless is the goal,
                like almost everything in web3. @@ -291,7 +292,7 @@ The bridge can never be stronger than the consensus on the source chain -- Most trustless way to interact with blockchain
                is to run a node +- Most trustless way to interact with blockchain
                is to run a node - This is true for individuals _and_ other blockchains - A blockchain is extremely resource constrained. - Run a source chain light client on the target chain @@ -392,9 +393,9 @@ One is to add a role of fishermen. They are responsible for noticing when the header candidate on the target chain is different from the one in the main source chain protocol and reporting this behavior back to the source chain so the validators can be slashed there. Two problems: -1. Fishermen have weak incentives. - If they do a good job there will be no equivocations and they will not get paid. -1. Target chain is relying on the foreign source chain to keep the bridge secure instead of owning that security itself. +1. Fishermen have weak incentives. + If they do a good job there will be no equivocations and they will not get paid. +1. Target chain is relying on the foreign source chain to keep the bridge secure instead of owning that security itself. The other is to have the relayer role require a security deposit. If it turns out that a relayer relays an attack header, that relayer is slashed and the relayer who reports it gets a reward. @@ -413,9 +414,9 @@ Relayers will expect to earn some reward for the opportunity cost of their stake - App users submit proofs -- Need a source chain transaction?
                +- Need a source chain transaction?
                Submit an spv-style transaction proof -- Need some source chain state?
                +- Need some source chain state?
                Submit a state proof
                diff --git a/content/blockchain-contracts/overview/slides.md b/content/blockchain-contracts/overview/slides.md index a65dc26..b4e9192 100644 --- a/content/blockchain-contracts/overview/slides.md +++ b/content/blockchain-contracts/overview/slides.md @@ -99,7 +99,12 @@ No individual actor, company, state, or coalition should be able to degrade any Notes: -So now we understand the goals of web3. How do we achieve them? The key is allowing users to agree on a shared history. The simplest blockchains do nothing more than timestamp and attest to a stream of historical records. In Web 2 users have no visibility into the history of the app. They must trust the provider to accurately represent the current state. By giving the service provider the power to change the story, we give them the power to shape our understanding of reality and consequently our behavior. +So now we understand the goals of web3. +How do we achieve them? The key is allowing users to agree on a shared history. +The simplest blockchains do nothing more than timestamp and attest to a stream of historical records. +In Web 2 users have no visibility into the history of the app. +They must trust the provider to accurately represent the current state. +By giving the service provider the power to change the story, we give them the power to shape our understanding of reality and consequently our behavior. ---v @@ -107,7 +112,9 @@ So now we understand the goals of web3. How do we achieve them? The key is allow > Any large-scale operation - whether a modern state, a medieval church, or an archaic tribe - is rooted in common stories that exist only in people's collective imaginations. -> Telling effective stories is not easy. The difficulty lies ... in convincing everyone else to believe it. Much of history revolves around this question: How does one convince millions of people to believe particular stories about gods, nations, or LLCs? +> Telling effective stories is not easy. +> The difficulty lies ... in convincing everyone else to believe it. +> Much of history revolves around this question: How does one convince millions of people to believe particular stories about gods, nations, or LLCs? @@ -123,7 +130,7 @@ _-- Yuval Noah Harari, Sapiens --_ If we agree on: -- The starting state
                (aka genesis state) +- The starting state
                (aka genesis state) - The history of transitions @@ -143,7 +150,11 @@ Then we _MUST_ agree on: Notes: -Now that we have a formal math-y model of systems that we care about, we can see that the notion of shared stories being powerful is more than slick language of philosophical mumbo jumbo. Even the term genesis state (or genesis block) is taken straight from mythology. We aren't newly discovering or inventing the idea that having a shared understanding of our past is important. It dates back to pre-history. We are just formalizing it and applying it to digital services. +Now that we have a formal math-y model of systems that we care about, we can see that the notion of shared stories being powerful is more than slick language of philosophical mumbo jumbo. +Even the term genesis state (or genesis block) is taken straight from mythology. +We aren't newly discovering or inventing the idea that having a shared understanding of our past is important. +It dates back to pre-history. +We are just formalizing it and applying it to digital services. --- @@ -188,11 +199,20 @@ What part of history is final? Notes: -First, each blockchain tracks some state machine. We've discussed several examples of what that might be already, we'll code some simple examples shortly, and we'll spend all of module 5 digging into how to create a blockchain-friendly production-ready state machine. +First, each blockchain tracks some state machine. +We've discussed several examples of what that might be already, we'll code some simple examples shortly, and we'll spend all of module 5 digging into how to create a blockchain-friendly production-ready state machine. -Next is the Blockchain Data structure. This data structure is basically a linked list of state transitions. But unlike the linked lists you studied in your data structures course, it isn't just linked by memory addresses or any other malleable thing. Instead it is cryptographically linked so that if anyone presents a different history, you can tell right away that you don't agree on a shared history. We'll dive into this data structure in the next lesson. +Next is the Blockchain Data structure. +This data structure is basically a linked list of state transitions. +But unlike the linked lists you studied in your data structures course, it isn't just linked by memory addresses or any other malleable thing. +Instead it is cryptographically linked so that if anyone presents a different history, you can tell right away that you don't agree on a shared history. +We'll dive into this data structure in the next lesson. -Finally, is a consensus mechanism. Defining a state machine alone does not uniquely define a history. There are many possible valid histories. Just like the many worlds interpretation of quantum mechanics. To really agree on the current state, we need to agree on which of the possible histories is the real one. +Finally, is a consensus mechanism. +Defining a state machine alone does not uniquely define a history. +There are many possible valid histories. +Just like the many worlds interpretation of quantum mechanics. +To really agree on the current state, we need to agree on which of the possible histories is the real one. ---v @@ -204,7 +224,9 @@ Finally, is a consensus mechanism. Defining a state machine alone does not uniqu -Uses an unspent transaction output (UTXO) model & Proof of Work (PoW) consensus. +Uses an unspent transaction output (UTXO) model & Proof of Work (PoW) consensus. + + Notes: @@ -256,10 +278,10 @@ Let the market decide.

                -#### Broad Definition _"Szabo definition"_ +#### Broad Definition _"Szabo definition"_
                A machine program with rules that we could have defined in a contract, but instead a machine performs or verifies performance.
                -#### Narrow Definition _"web3 definition"_ +#### Narrow Definition _"web3 definition"_
                A program that specifies how users can interact with a state machine and is deployed permissionlessly to a blockchain network
                diff --git a/content/blockchain-contracts/resources-fees-ordering/slides.md b/content/blockchain-contracts/resources-fees-ordering/slides.md index 062aa2c..52c6938 100644 --- a/content/blockchain-contracts/resources-fees-ordering/slides.md +++ b/content/blockchain-contracts/resources-fees-ordering/slides.md @@ -179,7 +179,7 @@ If it runs out of gas, it terminates the program. Notes: -[Source: Etherscan](https://etherscan.io/chart/gasprice) +[Source: Etherscan](https://etherscan.io/chart/gasprice) --- diff --git a/content/blockchain-contracts/structure/slides.md b/content/blockchain-contracts/structure/slides.md index f2ee8bc..74cab66 100644 --- a/content/blockchain-contracts/structure/slides.md +++ b/content/blockchain-contracts/structure/slides.md @@ -27,7 +27,8 @@ And it allows them to know whether they have identical histories in O(1) by just Notes: -This is a simplified blockchain. Each block has a pointer to the parent block as well as a payload. +This is a simplified blockchain. +Each block has a pointer to the parent block as well as a payload. ---v @@ -37,7 +38,9 @@ This is a simplified blockchain. Each block has a pointer to the parent block as Notes: -The pointer is a cryptographic hash of the parent block. This ensures data integrity throughout the entire history of the chain. This is the simplest form that a blockchain could take and indeed it allows us to agree on a shared history. +The pointer is a cryptographic hash of the parent block. +This ensures data integrity throughout the entire history of the chain. +This is the simplest form that a blockchain could take and indeed it allows us to agree on a shared history. ---v @@ -47,7 +50,8 @@ The pointer is a cryptographic hash of the parent block. This ensures data integ Notes: -This ensures data integrity throughout the entire history of the chain. This is the simplest form that a blockchain could take and indeed it allows us to agree on a shared history. +This ensures data integrity throughout the entire history of the chain. +This is the simplest form that a blockchain could take and indeed it allows us to agree on a shared history. ---v @@ -57,7 +61,9 @@ This ensures data integrity throughout the entire history of the chain. This is Notes: -The first block in the chain is typically called a the "Genesis block" named after the first book in the judaeo-christian mythology - The beginning of our shared story. The parent hash is chosen to be some specific value. Typically we use the all-zero hash, although any fixed widely agreed-upon value would also do. +The first block in the chain is typically called a the "Genesis block" named after the first book in the judaeo-christian mythology - The beginning of our shared story. +The parent hash is chosen to be some specific value. +Typically we use the all-zero hash, although any fixed widely agreed-upon value would also do. --- @@ -95,9 +101,15 @@ Somewhere else! Notes: -There is a state associated with each block. But typically the state is NOT stored in the block. This state information is redundant because it can always be obtained by just re-executing the history of the transitions. -It is possible to store the state in the blocks, but the redundancy is undesirable. It wastes disk space for anyone who wants to store the history of the chain. Storing the state in the block is not done by any moderately popular blockchain today. -If you _want_ to store the states, you are welcome to do so. Software that does this is known as an Archive node or an indexer. But it is stored separately from the block +There is a state associated with each block. +But typically the state is NOT stored in the block. +This state information is redundant because it can always be obtained by just re-executing the history of the transitions. +It is possible to store the state in the blocks, but the redundancy is undesirable. +It wastes disk space for anyone who wants to store the history of the chain. +Storing the state in the block is not done by any moderately popular blockchain today. +If you _want_ to store the states, you are welcome to do so. +Software that does this is known as an Archive node or an indexer. +But it is stored separately from the block ...Pause... One more time to make sure it sinks in: The state is NOT in the block. @@ -111,8 +123,16 @@ A cryptographic anchor to the state Notes: -Some data redundancy can be good to help avoid corruption etc. It is common for a block to contain a cryptographic fingerprint of -the state. This is known as a state root. You think of it as a hash of the state. In practice, the state is typically built into a Merkle tree like structure and the tree root is included. Not all blockchains do this. Notably bitcoin doesn't. But most do. We'll go into details about exactly how this state root is calculated for Substrate in the next two modules, but for now we just consider the state root to be some kind of cryptographic fingerprint. +Some data redundancy can be good to help avoid corruption etc. +It is common for a block to contain a cryptographic fingerprint of +the state. +This is known as a state root. +You think of it as a hash of the state. +In practice, the state is typically built into a Merkle tree like structure and the tree root is included. +Not all blockchains do this. +Notably bitcoin doesn't. +But most do. +We'll go into details about exactly how this state root is calculated for Substrate in the next two modules, but for now we just consider the state root to be some kind of cryptographic fingerprint. --- @@ -120,11 +140,14 @@ the state. This is known as a state root. You think of it as a hash of the state -A state machine can have different possible histories. These are called forks. +A state machine can have different possible histories. +These are called forks. Notes: -You can think of them like alternate realities. We need to decide which of the many possible forks is ultimately the "real" one. This is the core job of consensus and we will talk about it in two upcoming lessons in this module. +You can think of them like alternate realities. +We need to decide which of the many possible forks is ultimately the "real" one. +This is the core job of consensus and we will talk about it in two upcoming lessons in this module. ---v @@ -147,8 +170,10 @@ Before we even get to hardcore consensus, we can rule out _some_ possibilities b Notes: -The header is a minimal amount of information. In some ways it is like metadata. -The body contains the real "payload". It is almost always a batch of state transitions. +The header is a minimal amount of information. +In some ways it is like metadata. +The body contains the real "payload". +It is almost always a batch of state transitions. There are many name aliases for what is included in the body: - Transitions @@ -171,7 +196,8 @@ pub struct Block { Notes: -This example is from Substrate and as such it strives to be a general and flexible format, we will cover Substrate in more depth in the next module. This is representative of nearly all real-world blockchains +This example is from Substrate and as such it strives to be a general and flexible format, we will cover Substrate in more depth in the next module. +This is representative of nearly all real-world blockchains --- @@ -183,7 +209,8 @@ Headers are the _actual_ hash-linked list, not entire blocks. Notes: -The parent hash links blocks together (cryptographically linked list). The other info is handy for other infrastructure and applications (more on that later). +The parent hash links blocks together (cryptographically linked list). +The other info is handy for other infrastructure and applications (more on that later). ---v @@ -238,8 +265,10 @@ The parent hash links blocks together (cryptographically linked list). The other Notes: -Extrinsics root is a crypto link to the body of the block. It is very similar to the state root. -Consensus Digest is information necessary for the consensus algorithm to determine a block's validity. It varies widely with the consensus algorithm used and we will discuss it in two upcoming lectures. +Extrinsics root is a crypto link to the body of the block. +It is very similar to the state root. +Consensus Digest is information necessary for the consensus algorithm to determine a block's validity. +It varies widely with the consensus algorithm used and we will discuss it in two upcoming lectures. ---v @@ -320,7 +349,7 @@ What do you see here? ## Nodes -Software agents that participate in blockchain network.
                +Software agents that participate in blockchain network.
                May perform these jobs: @@ -397,7 +426,8 @@ Applications (maybe via their developers or users) pay for the privilege of havi Notes: Sometimes known as mempool (thanks bitcoin 🙄) -Authoring nodes determine the order of upcoming transactions. In some sense they can see the future. +Authoring nodes determine the order of upcoming transactions. +In some sense they can see the future. Foreshadow forks where players disagree on the rules History: dao fork bch fork diff --git a/content/blockchain-contracts/unstoppable-apps/slides.md b/content/blockchain-contracts/unstoppable-apps/slides.md index d2d9a94..e8f6cc6 100644 --- a/content/blockchain-contracts/unstoppable-apps/slides.md +++ b/content/blockchain-contracts/unstoppable-apps/slides.md @@ -79,7 +79,7 @@ In reality we strive for Absolute Unstoppability, but likely cannot grantee it i > Antifragility is beyond resilience or robustness. > The resilient resists shocks and stays the same; the antifragile gets better. > -> -- [Antifragile]() -- +> -- [Antifragile](https://en.wikipedia.org/wiki/Antifragile_%28book%29) --
              @@ -101,7 +101,7 @@ Notes: Hypothesis: a _absolutely_ Unstoppable App cannot exist. -We must make trade-offs out of all N properties
              that a _absolutely_ Unstoppable App would possess. +We must make trade-offs out of all N properties
              that a _absolutely_ Unstoppable App would possess. @@ -208,11 +208,11 @@ There are [valid criticisms](https://moxie.org/2022/01/07/web3-first-impressions -- Humans are cheap & lazy...
              +- Humans are cheap & lazy...
              No individuals run servers. - RPC node providers -- A _protocol_ improves
              slowly vs. a platform. -- False marketing,
              frauds, & scams! +- A _protocol_ improves
              slowly vs. a platform. +- False marketing,
              frauds, & scams!
              @@ -237,7 +237,7 @@ This is valid mostly in the present, we will discuss these and what we're buildi ## Prove it! -We use the word "proof" a lot...
              it means many things in [different contexts](https://en.wikipedia.org/wiki/Provable): +We use the word "proof" a lot...
              it means many things in [different contexts](https://en.wikipedia.org/wiki/Provable): @@ -261,7 +261,7 @@ Nuke proposes that when considering factors outside the consensus system, there ## 🔮 Oracle Problem -An [oracle](https://en.wikipedia.org/wiki/Category:Computation_oracles) provides eternal data to a consensus system.
              (i.e. a partial state of an external chain) +An [oracle](https://en.wikipedia.org/wiki/Category:Computation_oracles) provides eternal data to a consensus system.
              (i.e. a partial state of an external chain) The [oracle problem](https://blog.chain.link/what-is-the-blockchain-oracle-problem/) relates to the _trust_ in the oracle. @@ -280,7 +280,7 @@ Notes: -- known bounds of operation
              _assumed_ impossible +- known bounds of operation
              _assumed_ impossible - death spirals
              @@ -314,7 +314,9 @@ Notes: - Great talk by the author: reference talk by book author. -Example: irrational actors can be represented in a very simple model as a completely random act, or opposite act of what a rational actor would do. If you "fuzz" you system you may discover fragility to irrational actions that could undermine your system. Perhaps it's far easier and more likely than it at first appears to experience a black swan event. +Example: irrational actors can be represented in a very simple model as a completely random act, or opposite act of what a rational actor would do. +If you "fuzz" you system you may discover fragility to irrational actions that could undermine your system. +Perhaps it's far easier and more likely than it at first appears to experience a black swan event. - Image [source](https://en.wikipedia.org/wiki/Nassim_Nicholas_Taleb#/media/File:Genealogy_map_of_topics_treated_by_Nassim_Taleb.jpg) - Describes the various categories of uncertainty, epistemology limits and statistical subjects touching on Taleb's Black swan / antifragility etc. ideas @@ -442,17 +444,17 @@ If running _one_ node is burdensome, try multiple. ## Trustless Messaging -In order to handle messages _without trust_,
              systems must share common finality guarantees. +In order to handle messages _without trust_,
              systems must share common finality guarantees. -`A` should never process a message from `B`,
              where `B` is reverted and `A` is not. +`A` should never process a message from `B`,
              where `B` is reverted and `A` is not. ---v ## A Note on Synchronicity -Smart contracts on a single chain (e.g. Ethereum)
              can interact trustlessly because of their shared view of finality. +Smart contracts on a single chain (e.g. Ethereum)
              can interact trustlessly because of their shared view of finality. -Asynchronous systems can also share finality.
              +Asynchronous systems can also share finality.
              i.e., be members of the same consensus system. ---v @@ -480,7 +482,7 @@ Notes: ## Mining Pools -Proof of Work authority sets have no finite bound.
              +Proof of Work authority sets have no finite bound.
              But people like to organize. \[Collaborating | Colluding\] authority sets creates risk. @@ -518,15 +520,15 @@ Security is always a finite resource: ## Security Dilution -Consensus systems compete for security,
              and they have reason to attack each other. +Consensus systems compete for security,
              and they have reason to attack each other. -Emergence of obscure/niche "Proof of X" algorithms
              to shelter from attack only goes so far. +Emergence of obscure/niche "Proof of X" algorithms
              to shelter from attack only goes so far. ---v ## ⚔ Blockchain Wars -Systems with high security have the
              incentive to attack systems with low security
              whom they perceive as competitors. +Systems with high security have the
              incentive to attack systems with low security
              whom they perceive as competitors. > For fun and profit. @@ -552,9 +554,9 @@ Notes: ---v -## Proof of...
              Nothing at Stake +## Proof of...
              Nothing at Stake -Forks are "free" to vote in favor of...
              +Forks are "free" to vote in favor of...
              vote on them all! (If you are not eventually slashed!) @@ -566,15 +568,15 @@ Notes: - Unlike PoW where voting on a chain costs something _extrinsic_ to the system, PoS has only _intrinsic_ measures to do accounting of consensus rules. - **Critical:** This was a problem with early naive implementations of PoS. Modern PoS schemes avoid this specific problem by having the security deposit and slashing for equivocation (in a few slides) -- Good explainer, source of image: +- Good explainer, source of image: ---v -## Proof of...
              _Relatively_ Nothing at Stake +## Proof of...
              _Relatively_ Nothing at Stake -Risk-to-reward ratio of attacks is
              _relative to the valuation of the staked assets_. +Risk-to-reward ratio of attacks is
              _relative to the valuation of the staked assets_. -Rational actors take into account
              _extrinsic motivators_ in calculating the highest reward. +Rational actors take into account
              _extrinsic motivators_ in calculating the highest reward. > What might it cost to successfully attack? @@ -645,11 +647,11 @@ Nuke argue this is the same for the sum of all contracts valuations on something - Equivocation - - Authorship: Proposing mutually
              exclusive chains - - Finality: Voting for mutually
              exclusive chains to be final + - Authorship: Proposing mutually
              exclusive chains + - Finality: Voting for mutually
              exclusive chains to be final - Invalidity - Lack of availability -- **Intentional protocol abuse** ([selfish mining](https://golden.com/wiki/Selfish_mining_attack-39PMNNA)) +- **Intentional protocol abuse** ([selfish mining](https://golden.com/wiki/Selfish_mining_attack-39PMNNA))
              @@ -677,21 +679,22 @@ Those who _choose_ to become authorities should be liable for their actions. Some types of misbehavior are harder to prove than others. -**Equivocation** is simple:
              Someone can just produce two signed messages as cryptographic proof. +**Equivocation** is simple:
              Someone can just produce two signed messages as cryptographic proof. Others rely on challenge-response games and dispute resolution. Notes: -Nothing at stake solution, with the possible caveat of long range attacks. [Weak subjectivity](https://blog.ethereum.org/2014/11/25/proof-stake-learned-love-weak-subjectivity) can still potentially cause the same behavior in a much harder to orchestra way, with bad actors having already have their stake released to produce a valid, finalized fork. +Nothing at stake solution, with the possible caveat of long range attacks +[Weak subjectivity](https://blog.ethereum.org/2014/11/25/proof-stake-learned-love-weak-subjectivity) can still potentially cause the same behavior in a much harder to orchestra way, with bad actors having already have their stake released to produce a valid, finalized fork. ---v -## Design Considerations
              in Polkadot +## Design Considerations
              in Polkadot - More validators increases the state transition throughput of the network: parachains. - Individual shards have full economic freedom by being members of a larger consensus system. -- _Superlinear_ slashing puts colluding validators at existential risk,
              while well-meaning ones should have little to worry about). +- _Superlinear_ slashing puts colluding validators at existential risk,
              while well-meaning ones should have little to worry about). Notes: @@ -753,8 +756,8 @@ Not realized as possible by many until it quietly became the norm. ## Maximal Extractable Value -> An environment in which detection means certain death...
              -> ...identifying someone’s location is as good as directly destroying them.

              +> An environment in which detection means certain death...
              +> ...identifying someone’s location is as good as directly destroying them.

              > -- [Ethereum is a Dark Forest](https://www.paradigm.xyz/2020/08/ethereum-is-a-dark-forest) -- Notes: @@ -769,7 +772,7 @@ This is now the norm on Ethereum at least, and further _it's becoming institutio ## 👼 Flashbots -> Flashbots is a research and development organization formed to mitigate the negative externalities posed by Maximal Extractable Value (MEV) to stateful blockchains, starting with Ethereum.

              +> Flashbots is a research and development organization formed to mitigate the negative externalities posed by Maximal Extractable Value (MEV) to stateful blockchains, starting with Ethereum.

              > -- [Flashbots](https://www.flashbots.net/) -- Notes: @@ -815,9 +818,10 @@ Notes: Notes: - + -- code is unstoppable, but platform _can_ sensor. ability -> responsibility (we may talk more on that latter) +- code is unstoppable, but platform _can_ sensor. + Ability -> responsibility (we may talk more on that latter) ---v @@ -834,7 +838,7 @@ Notes: - Pressure from peers through breaking norms, perhaps even losing of authority in consensus due to this. Peer reputation in computer networks, and here also in human ones. - Sometimes social pressures are healthy for the system, sometimes toxic depending on point of view and who benefits! -- In monero "run your own node" culture helps keep it decentralized.
              +- In monero "run your own node" culture helps keep it decentralized.
              Bitcoin big block wars show social pressures help decide the canonical forks. - Normalizing MEV for the profit of middlemen, providing extraction services in the worst case. @@ -877,9 +881,9 @@ Notes: ## Final Thoughts -- Complexity generally increases the risks of failures, but we should not fear it.
              +- Complexity generally increases the risks of failures, but we should not fear it.
              $~~~$_Hypothesis: this \_usually_ makes systems more brittle.\_ -- Observable behavior trumps models and theory.
              +- Observable behavior trumps models and theory.
              $~~~$_Complex systems are not intuitive and may show your assumptions and models are wrong!_ - This lesson was a _start_ down holes... $~~~$_We encourage you to keep diving deeper!_ @@ -932,7 +936,7 @@ Perhaps assigned informally to everyone to watch in the next few days. > It seizes power from dominate forms of power: governments, corporations, states, associations, cultures, religions. > It seizes power, from these big things and gives it to little people. > And sooner or later, the people who are losing their undeserved, abusively applied power will start to fight back. -> And at that point, we will start to find out how unstoppable our code is.

              +> And at that point, we will start to find out how unstoppable our code is.

              > -- Andreas Antonopoulos -- ---v @@ -940,7 +944,7 @@ Perhaps assigned informally to everyone to watch in the next few days. ## Can't vs. Won't > The moment you go over the the line from "can't to won't, what started as an ability becomes a responsibility. -> And then if you claim that you don't have the ability anymore, that responsibility just became negligence, criminal negligence.

              +> And then if you claim that you don't have the ability anymore, that responsibility just became negligence, criminal negligence.

              > -- Andreas Antonopoulos -- Notes: @@ -962,7 +966,7 @@ Decentralized Autonomous Organizations ([DAOs](https://www.investopedia.com/tech ## Democratic Systems -Democratic Mediums is a directory of patterns
              for decision, deliberation, and noise. +Democratic Mediums is a directory of patterns
              for decision, deliberation, and noise. @@ -982,7 +986,7 @@ Many novel and niece definitions in this wiki. ## Modeling Behavior -> [Token Engineering](https://tokenengineeringcommunity.github.io/website/)
              +> [Token Engineering](https://tokenengineeringcommunity.github.io/website/)
              > {especially the Academy & cadCAD Edu} Notes: diff --git a/content/blockchain-contracts/utxo-privacy/slides.md b/content/blockchain-contracts/utxo-privacy/slides.md index 882e3ae..b867709 100644 --- a/content/blockchain-contracts/utxo-privacy/slides.md +++ b/content/blockchain-contracts/utxo-privacy/slides.md @@ -28,7 +28,8 @@ duration: 30min ## Bitcoin -- Bitcoin specifies the spent output. This satisfies membership and linkability +- Bitcoin specifies the spent output. + This satisfies membership and linkability - Each Bitcoin output has a small, non-Turing complete program (Script) specifying how it can be spent - Each input has a `scriptSig` which proves the script is satisfied and this is an authorized spend (ownership) - The outputs cannot exceed the inputs, and the remainder becomes the fee (sum check) @@ -77,7 +78,7 @@ duration: 30min - Amount - Owner - Mask -- All in a single
              +- All in a single
              Pedersen commitment
              diff --git a/content/contribute/copy-paste-slides/slides.md b/content/contribute/copy-paste-slides/slides.md index 9e85f3c..eb4401c 100644 --- a/content/contribute/copy-paste-slides/slides.md +++ b/content/contribute/copy-paste-slides/slides.md @@ -118,7 +118,7 @@ pub type Executive = frame_executive::Executive< Use `o` to open the overview mode and explore slides here. -You can see the source of these slides to copy&paste
              +You can see the source of these slides to copy&paste
              as slide templates in your slides! @@ -138,14 +138,14 @@ as slide templates in your slides! ### Center 1 -Using
              `` +Using
              `` ### Center 2 -Using
              `` +Using
              ``
              @@ -161,14 +161,14 @@ Using
              `` ### Center 1 -Using
              `` +Using
              `` ### Center 2 -Using
              `` +Using
              `` @@ -183,21 +183,21 @@ Using
              `` ### Left -Using
              `` +Using
              `` ### Center -Using
              `` +Using
              `` ### Right -Using
              `` +Using
              `` @@ -213,21 +213,21 @@ Using
              `` ### Left -Using
              `` +Using
              `` ### Center -Using
              `` +Using
              `` ### Right -Using
              `` +Using
              `` @@ -308,7 +308,7 @@ svg, png, gif, ... anything that works on the web should work here! Notes: Image source: -License: +License: ---v @@ -776,7 +776,7 @@ First of all lets see some examples of diagrams that Mermaid can show with its i ### [A Flowchart](https://mermaid.js.org/syntax/flowchart.html) - + %%{init: {'theme': 'dark', 'themeVariables': { 'darkMode': true }}}%% flowchart TD A(Start) --> B{Is it?}; @@ -784,7 +784,7 @@ First of all lets see some examples of diagrams that Mermaid can show with its i C --> D(Rethink); D --> B; B -- No ----> E(End); - + ---v diff --git a/content/contribute/index.md b/content/contribute/index.md index a3c24b8..cb1bb1a 100644 --- a/content/contribute/index.md +++ b/content/contribute/index.md @@ -261,17 +261,18 @@ They typically are identical to: This book, and all content within have style and typographic conventions that, where practical, have tooling to help everyone conform to them. -### Formatting Markdown, TOML, JSON +### Formatting -We enforce the use of a few formatters, the primary one being [Prettier](https://prettier.io/) that is included in the dev-dependencies for this repository. -In `package.json` used in the `cargo make` tooling we include easy access to run this: +All Markdown, TOML, JSON, Typescript, and Javascript files in this repository are formatter with [dprint](https://dprint.dev/). +The setting for this formatter are found in `.dprint.json`. +We use `cargo make` to run this: ```sh -# This will format all `content/*.md` files +# This will format all files SUPER FAST after the first run is cached makers f ``` -If (and only if) formatting _breaks_ markdown from rendering correctly, you may use `` preceding a block in markdown to skip formatting like this: +If (and only if) formatting _breaks_ Markdown from rendering correctly, you may use `` preceding a block in markdown to skip formatting like this: ````markdown @@ -291,40 +292,66 @@ If (and only if) formatting _breaks_ markdown from rendering correctly, you may
              ``` + + + +Some text + +* other text +* testing + + ```` -The above ` ```html ` block will not be formatted. +See [the docs on Markdown for dprint](https://dprint.dev/plugins/markdown/#ignore-comments) for more. ### Checking Links -To ensure all `*.md` contain no broken links within them, we have included a [simple link checker](https://github.com/tcort/markdown-link-check) you can run per module of content with: +To ensure all `*.md` and `.html` files contain no broken links within them, we use a [the `mlc` link checker](https://github.com/becheran/mlc). +Run with: ```sh -# Link check a single file: -makers links-for -# Regex glob match works too: -makers links-for ./content/contribute/**/*.md - # Link check all content files makers l + +# Link check a single file: +makers links-for +# Link check a directory, recursively +makers links-for <./content/some-dir/inner-dir> ``` -The checker uses the `.github/workflows/mlc_config.json` configuration, primarily used to _globally_ ignore specific common URLs that throw errors, in error 😛. +The checker configuration is set ine `Makefile.rs` task to see settings (the `.mlc.toml` config.github/workflows/check.ymlrimarily used to _globally_ ignore specific common URLs that throw errors, in error 😛. _Notice that ignored links must be check from time to time manually!_ _Thus don't use this unless explicitly needed, rather use a know good URL if at all possible, perhaps from the _ The same tool is also run by our CI on all files for all pushes to all branches. See the `.github/workflows/link-check.yml` file in this repo for details. -> You can ignore the link check for a single line by post-fixing it with ``: +> You can ignore the link check for a `regex` compliant entry in: +> +> 1. `.mlc.toml` +> 1. `.github/workflows/check.yml` +> 1. `Makefile.rs` > -> ```markdown -> Some [private](nonono) or intentionally [broken link](FIXME). ` -> ``` +> [Eventually](https://github.com/becheran/mlc/issues/78) just `.mlc.toml` will do. + +### Checking Images + +In order to ensure that there are no issues with images in this book, we check for: + +1. Broken links to images that will not be found in the build. +1. Orphaned image files - not linked to at all from the book. + +```sh +# Link check all `` tags +makers img +``` + +Please **_delete_** any assets you do not need, we can always `git recover` at a latter time to bring them back in 💽. ## CI -On any merge with `main`, the CI is tasked with building the book and deploying a hosted version of it. +1. `.github/workflows/pages.yml` - On any merge with `main`, the CI is tasked with building the book and deploying a hosted version of it. +1. `.github/workflows/check.yml` - On any merge with `main`, the CI is tasked with checking book for any issues with format, links, and images. See `.github/workflows/` in this repository for more details. -Other tasks mostly stand alone from the `cargo make` tooling suggested in development workflows at this time, but does require the `yarn` tooling to properly build and test things. -The workflows consist of minimal checks for style, common errors, formatting, etc. +Other tasks mostly stand alone from the `cargo make` tooling suggested in development workflows at this time, but some require the `yarn` tooling to properly build and test things. diff --git a/content/cryptography/_materials/many-time-pad.md b/content/cryptography/_materials/many-time-pad.md index 8be8222..204ce83 100644 --- a/content/cryptography/_materials/many-time-pad.md +++ b/content/cryptography/_materials/many-time-pad.md @@ -36,7 +36,7 @@ Your task is to use [cryptanalysis](https://en.wikipedia.org/wiki/Cryptanalysis) 1. Team up with 2-4 students to complete this activity. 1. Briefly inspect the ciphertext to see if you can identify patterns that may hint some things about their origin. 1. Research based on what we know bout the messages to find clues to help come up with a theory and game plan to complete your task. -1. Write a program in Rust that finds the key to generate the plaintext from the provided cipher texts.
              +1. Write a program in Rust that finds the key to generate the plaintext from the provided cipher texts.
              The general steps are: 1. Find the length of the longest input cipher text. diff --git a/content/cryptography/addresses/slides.md b/content/cryptography/addresses/slides.md index d3a61ea..87e56c1 100644 --- a/content/cryptography/addresses/slides.md +++ b/content/cryptography/addresses/slides.md @@ -75,7 +75,7 @@ Recall, both symmetric and asymmetric cryptography require a secret. ## Mnemonics -Many wallets use a dictionary of words and give people phrases,
              often 12 or 24 words, as these are easier to back up/recover than byte arrays. +Many wallets use a dictionary of words and give people phrases,
              often 12 or 24 words, as these are easier to back up/recover than byte arrays. Notes: @@ -116,7 +116,7 @@ _The first 5 words of the [BIP39 English dictionary](https://github.com/bitcoin/ Of course, the secret key is a point on an elliptic curve, not a phrase. -BIP39 applies 2,048 rounds of the SHA-512 hash function
              to the mnemonic to derive a 64 byte key. +BIP39 applies 2,048 rounds of the SHA-512 hash function
              to the mnemonic to derive a 64 byte key. Substrate uses the entropy byte array from the mnemonic. @@ -204,7 +204,7 @@ Hierarchical Deterministic Key Derivation ## Hard vs. Soft -Key derivation allows one to derive (virtually limitless)
              child keys from one "parent". +Key derivation allows one to derive (virtually limitless)
              child keys from one "parent". Derivations can either be "hard" or "soft". diff --git a/content/cryptography/advanced-signatures/slides.md b/content/cryptography/advanced-signatures/slides.md index 29115d2..77a4a28 100644 --- a/content/cryptography/advanced-signatures/slides.md +++ b/content/cryptography/advanced-signatures/slides.md @@ -36,7 +36,7 @@ Certificate transparency: [explanation](https://certificate.transparency.dev/how ### Certificates in Web3 -We are building systems that don't have a "Certificate Authority".
              +We are building systems that don't have a "Certificate Authority".
              But we can still use certificates in some niche instances. Notes: @@ -51,11 +51,11 @@ Potential example to give verbally: ### Multi-Signatures -We often want signatures that must be signed
              by multiple parties to become valid. +We often want signatures that must be signed
              by multiple parties to become valid. -- Require some threshold of members to
              agree to a message +- Require some threshold of members to
              agree to a message - Protect against key loss
              @@ -68,7 +68,7 @@ We often want signatures that must be signed
              by multiple parties to become v - Verifier enforced - Cryptographic threshold -- Cryptographic non-threshold
              (a.k.a. signature aggregation) +- Cryptographic non-threshold
              (a.k.a. signature aggregation) --- @@ -105,7 +105,7 @@ _Example: "The five key holders have signed this message."_ ### Key Generation for Multi-Sigs -In regular multi-signatures,
              signatures from individual public keys are aggregated. +In regular multi-signatures,
              signatures from individual public keys are aggregated. Each participant can choose their own key to use for the multi-signature. @@ -197,7 +197,7 @@ However... ### Schnorr and BLS Summary -Schnorr & BLS multi-signatures avoid complicating verifier logic,
              but introduce user experience costs such as: +Schnorr & BLS multi-signatures avoid complicating verifier logic,
              but introduce user experience costs such as: - DKG protocols - Reduced key derivation ability diff --git a/content/cryptography/basic-signatures/slides.md b/content/cryptography/basic-signatures/slides.md index 58fbe5a..429aa95 100644 --- a/content/cryptography/basic-signatures/slides.md +++ b/content/cryptography/basic-signatures/slides.md @@ -12,10 +12,10 @@ duration: 1 hour Signature libraries should generally all expose some basic functions: -- `fn generate_key(r) -> sk;`
              Generate a `sk` (secret key) from some input `r`. -- `fn public_key(sk) -> pk;`
              Return the `pk` (public key) from a `sk`. -- `fn sign(sk, msg) -> signature;`
              Takes `sk` and a message; returns a digital signature. -- `fn verify(pk, msg, signature) -> bool;`
              For the inputs `pk`, a message, and a signature; returns whether the signature is valid. +- `fn generate_key(r) -> sk;`
              Generate a `sk` (secret key) from some input `r`. +- `fn public_key(sk) -> pk;`
              Return the `pk` (public key) from a `sk`. +- `fn sign(sk, msg) -> signature;`
              Takes `sk` and a message; returns a digital signature. +- `fn verify(pk, msg, signature) -> bool;`
              For the inputs `pk`, a message, and a signature; returns whether the signature is valid. Notes: @@ -44,7 +44,7 @@ See the Jupyter notebook and/or HackMD cheat sheet for this lesson. ## Hash Functions -There are two lessons dedicated to hash functions.
              But they are used as part of all signing processes. +There are two lessons dedicated to hash functions.
              But they are used as part of all signing processes. For now, we only concern ourselves with using Blake2. @@ -52,7 +52,7 @@ For now, we only concern ourselves with using Blake2. ## Hashed Messages -As mentioned in the introduction,
              it's often more practical to sign the hash of a message. +As mentioned in the introduction,
              it's often more practical to sign the hash of a message. Therefore, the sign/verify API may be _used_ like: @@ -63,7 +63,7 @@ Therefore, the sign/verify API may be _used_ like: -Where `H` is a hash function (for our purposes, Blake2).
              +Where `H` is a hash function (for our purposes, Blake2).
              This means the verifier will need to run the correct hash function on the message. --- @@ -85,10 +85,10 @@ If a hash is signed, you can prove a signature is valid _without_ telling anyone ## Signing Payloads -Signing payloads are an important part of system design.
              +Signing payloads are an important part of system design.
              Users should have credible expectations about how their messages are used. -For example, when a user authorizes a transfer,
              they almost always mean just one time. +For example, when a user authorizes a transfer,
              they almost always mean just one time. Notes: @@ -110,7 +110,7 @@ Note that signing and encryption are _not_ inverses. ## Replay Attacks -Replay attacks occur when someone intercepts and resends a valid message.
              +Replay attacks occur when someone intercepts and resends a valid message.
              The receiver will carry out the instructions since the message contains a valid signature. @@ -130,7 +130,7 @@ Tell the story of Ethereum Classic replays. ## Replay Attack Prevention -Signing payloads should be designed so that they can
              only be used _one time_ and in _one context_.
              +Signing payloads should be designed so that they can
              only be used _one time_ and in _one context_.
              Examples: @@ -164,7 +164,7 @@ Examples: ## Sr25519 -Sr25519 addresses several small risk factors that emerged
              from Ed25519 usage by blockchains. +Sr25519 addresses several small risk factors that emerged
              from Ed25519 usage by blockchains. --- diff --git a/content/cryptography/encryption/slides.md b/content/cryptography/encryption/slides.md index def757a..567f155 100644 --- a/content/cryptography/encryption/slides.md +++ b/content/cryptography/encryption/slides.md @@ -20,7 +20,7 @@ duration: 1 hour ## Symmetric Cryptography -Symmetric encryption assumes all parties begin with some shared secret information, a potentially very difficult requirement.
              The shared secret can then be used to protect further communications from others who do not know this secret. +Symmetric encryption assumes all parties begin with some shared secret information, a potentially very difficult requirement.
              The shared secret can then be used to protect further communications from others who do not know this secret. In essence, it gives a way of _extending_ a shared secret over time. @@ -38,9 +38,9 @@ Examples: ChaCha20, Twofish, Serpent, Blowfish, XOR, DES, AES Symmetric encryption libraries should generally all expose some basic functions: -- `fn generate_key(r) -> k;`
              Generate a `k` (secret key) from some input `r`. -- `fn encrypt(k, msg) -> ciphertext;`
              Takes `k` and a message; returns the ciphertext. -- `fn decrypt(k, ciphertext) -> msg;`
              Takes `k` and a ciphertext; returns the original message. +- `fn generate_key(r) -> k;`
              Generate a `k` (secret key) from some input `r`. +- `fn encrypt(k, msg) -> ciphertext;`
              Takes `k` and a message; returns the ciphertext. +- `fn decrypt(k, ciphertext) -> msg;`
              Takes `k` and a ciphertext; returns the original message. It always holds that `decrypt(k, encrypt(k, msg)) == msg`. @@ -73,7 +73,7 @@ Notes: There is cryptographic proof that the secret was known to the producer of the encrypted message. -
              +
              _However_, knowledge of the secret is not restricted to one party: Both (or all) parties in a symmetrically encrypted communication know the secret. Additionally, in order to prove this to anyone, they must _also_ gain knowledge of the secret. @@ -186,10 +186,10 @@ i.e. Public key is used to encrypt but a different, _secret_, key must be used t Asymmetric encryption libraries should generally all expose some basic functions: -- `fn generate_key(r) -> sk;`
              Generate a `sk` (secret key) from some input `r`. -- `fn public_key(sk) -> pk;`
              Generate a `pk` (public key) from the private key `sk`. -- `fn encrypt(pk, msg) -> ciphertext;`
              Takes the public key and a message; returns the ciphertext. -- `fn decrypt(sk, ciphertext) -> msg;`
              For the inputs `sk` and a ciphertext; returns the original message. +- `fn generate_key(r) -> sk;`
              Generate a `sk` (secret key) from some input `r`. +- `fn public_key(sk) -> pk;`
              Generate a `pk` (public key) from the private key `sk`. +- `fn encrypt(pk, msg) -> ciphertext;`
              Takes the public key and a message; returns the ciphertext. +- `fn decrypt(sk, ciphertext) -> msg;`
              For the inputs `sk` and a ciphertext; returns the original message. It always holds that `decrypt(sk, encrypt(public_key(sk), msg)) == msg`. diff --git a/content/cryptography/exotic-primitives/slides.md b/content/cryptography/exotic-primitives/slides.md index e8dd85a..9021587 100644 --- a/content/cryptography/exotic-primitives/slides.md +++ b/content/cryptography/exotic-primitives/slides.md @@ -22,7 +22,7 @@ duration: 1 hour --- -## Verifiable Random Functions
              (VRFs) +## Verifiable Random Functions
              (VRFs) @@ -53,7 +53,7 @@ The output of verification being an option represents the possibility of an inva - Output is a deterministic function of _key_ and _input_ - i.e. eval should be deterministic - It should be pseudo-random -- But until the VRF is revealed, only the holder
              of the secret key knows the output +- But until the VRF is revealed, only the holder
              of the secret key knows the output - Revealing output does not leak secret key --- @@ -161,7 +161,7 @@ If the messages are not far apart, it is impossible to distinguish in many cases With erasure coding, we extend each message magically so they are different enough. The sender and receiver know the same encoding procedure. These extensions will be very different, even if the messages are similar. -`msg1``jdf` and `msg2``ajk` +`msg1` `jdf` and `msg2` `ajk` Notes: @@ -182,7 +182,7 @@ The magic here is polynomials, and the fact that a polynomial of degree $n$ is c ## Erasure Coding Classical use - Used for noisy channels -- If a few bits of the coded data are randomly flipped,
              we can still recover the original data +- If a few bits of the coded data are randomly flipped,
              we can still recover the original data - Typically $n$ is not much bigger than $k$ --- @@ -243,16 +243,16 @@ Notes: ## Proxy Reencryption API -- `fn encrypt(pk, msg) -> ciphertext;`
              Takes your public key and a message; returns ciphertext. -- `fn decrypt(sk, ciphertext) -> msg;`
              Takes your private key and a ciphertext; returns the message. -- `fn get_reencryption_key(sk, pk) -> rk;`
              Takes your private key, and the recipient's public key; returns a reencryption key. -- `fn reencrypt(rk, old_ciphertext) -> new_ciphertext;`
              Take a reencryption key, and transform ciphertext to be decrypted by new party. +- `fn encrypt(pk, msg) -> ciphertext;`
              Takes your public key and a message; returns ciphertext. +- `fn decrypt(sk, ciphertext) -> msg;`
              Takes your private key and a ciphertext; returns the message. +- `fn get_reencryption_key(sk, pk) -> rk;`
              Takes your private key, and the recipient's public key; returns a reencryption key. +- `fn reencrypt(rk, old_ciphertext) -> new_ciphertext;`
              Take a reencryption key, and transform ciphertext to be decrypted by new party. --- ## ZK Proofs -How do we do private operations on a public blockchain
              and have everyone know that they were done correctly? +How do we do private operations on a public blockchain
              and have everyone know that they were done correctly? Notes: @@ -361,11 +361,11 @@ Polkadot already scales better! -A user has private data, but we can show
              publicly that this private data is correctly used.
              +A user has private data, but we can show
              publicly that this private data is correctly used.
              An example would a private cryptocurrency: - Keep who pays who secret -- Keep amounts secret,
              _But show they are positive!_ +- Keep amounts secret,
              _But show they are positive!_
              @@ -390,26 +390,26 @@ To do everything well, ZK-SNARKs are needed in e.g. ZCash and its many derivativ - Slow prover time for general computation - To be fast, need to hand optimize -- Very weird computation model:
              +- Very weird computation model:
              Non-deterministic arithmetic circuits --- ## Downsides Conclusion? -- So if you want to use this for a component,
              expect a team of skilled people to work for at least a year on it... -- But if you are watching this 5 years later,
              people have built tools to make it less painful. +- So if you want to use this for a component,
              expect a team of skilled people to work for at least a year on it... +- But if you are watching this 5 years later,
              people have built tools to make it less painful. --- -## Succinct Proving
              with Cryptography? +## Succinct Proving
              with Cryptography? - ZK friendly hashes - Non-hashed based data structures - RSA accumulators - - Polynomial commitment based
              + - Polynomial commitment based
              (Verkle trees)
              diff --git a/content/cryptography/hash-based-data-structures/slides.md b/content/cryptography/hash-based-data-structures/slides.md index 637ed04..e7611af 100644 --- a/content/cryptography/hash-based-data-structures/slides.md +++ b/content/cryptography/hash-based-data-structures/slides.md @@ -8,7 +8,7 @@ duration: 1 hour --- -## Comparison to
              Pointer Based Data Structures +## Comparison to
              Pointer Based Data Structures - A hash references the _content_ of some data; - A pointer tells you where to find it; @@ -63,7 +63,7 @@ If we compute the correct root, this proves that the leaf was in the tree ## Security -Collision resistance: we reasonably assume only one preimage for each hash,
              therefore making the data structure's linkage persistent and enduring (until the cryptography becomes compromised 😥). +Collision resistance: we reasonably assume only one preimage for each hash,
              therefore making the data structure's linkage persistent and enduring (until the cryptography becomes compromised 😥). Notes: @@ -73,7 +73,7 @@ Explain what could happen when this fails. ## Proof Sizes -Proof of a leaf has size $O(\log n)$
              and so do proofs of updates of a leaf +Proof of a leaf has size $O(\log n)$
              and so do proofs of updates of a leaf --- @@ -83,7 +83,7 @@ Proof of a leaf has size $O(\log n)$
              and so do proofs of updates of a leaf ## Key-value database -The data structure stores a map `key -> value`.
              +The data structure stores a map `key -> value`.
              We should be able to: @@ -182,7 +182,7 @@ Additionally, if the size of a value is particularly large, it is replaced with --- -## Computational and Storage
              Trade-offs +## Computational and Storage
              Trade-offs What radix $r$ is best? diff --git a/content/cryptography/hashes/slides.md b/content/cryptography/hashes/slides.md index 937e827..a5b3a22 100644 --- a/content/cryptography/hashes/slides.md +++ b/content/cryptography/hashes/slides.md @@ -10,7 +10,7 @@ duration: 1 hour ## Introduction -We often want a succinct representation of some data
              with the expectation that we are referring to the same data. +We often want a succinct representation of some data
              with the expectation that we are referring to the same data. ##### A "fingerprint" @@ -23,9 +23,9 @@ We often want a succinct representation of some data
              with the expectation th 1. Accept unbounded size input 1. Map to a bounded output 1. Be fast to compute -1. Be computable strictly one-way
              (difficult to find a pre-image for a hash) -1. Resist pre-image attacks
              (attacker controls one input) -1. Resist collisions
              (attacker controls both inputs) +1. Be computable strictly one-way
              (difficult to find a pre-image for a hash) +1. Resist pre-image attacks
              (attacker controls one input) +1. Resist collisions
              (attacker controls both inputs)
              @@ -165,7 +165,7 @@ Source: ## Non-Cryptographic Hash Functions -Non-cryptographic hash functions provide weaker
              guarantees in exchange for performance. +Non-cryptographic hash functions provide weaker
              guarantees in exchange for performance. They are OK to use when you know that the input is not malicious. @@ -175,7 +175,7 @@ They are OK to use when you know that the input is not malicious. ## One Way -Given a hash, it should be difficult to find an input value (pre-image)
              that would produce the given hash. +Given a hash, it should be difficult to find an input value (pre-image)
              that would produce the given hash. That is, given `H(x)`, it should be difficult to find `x`. @@ -187,7 +187,7 @@ We sometimes add random bytes to pre-images to prevent guesses based on context ## Second Pre-Image Attacks -Given a hash and a pre-image, it should be difficult to find _another_
              pre-image that would produce the same hash. +Given a hash and a pre-image, it should be difficult to find _another_
              pre-image that would produce the same hash. Given `H(x)`, it should be difficult to find any `x'` @@ -201,7 +201,7 @@ Since most signature schemes perform some internal hashing, this second pre-imag ## Collision Resistance -It should be difficult for someone to find two messages that
              hash to the same value. +It should be difficult for someone to find two messages that
              hash to the same value. It should be difficult to find an `x` and `y` @@ -233,7 +233,7 @@ single hash collision often results in the hash function being considered unsafe > With 23 people, there is a 6% chance that someone will be born on a specific date, but a 50% chance that two share a birthday. -- Must compare each output with every other, not with a single one.
              +- Must compare each output with every other, not with a single one.
              - Number of possible "hits" increases exponentially for more attempts, reducing the expected success to the square-root of what a specific target would be.
              @@ -353,7 +353,7 @@ This is key in digital signatures. However, it's important to realize that if $D ## Content-Derived Indexing -Hash functions can be used to generate deterministic
              and unique lookup keys for databases. +Hash functions can be used to generate deterministic
              and unique lookup keys for databases. Notes: @@ -363,9 +363,9 @@ Given some fixed property, like an ID and other metadata the user knows beforeha ## Data Integrity Checks -Members of a peer-to-peer network may host and share
              file chunks rather than large files. +Members of a peer-to-peer network may host and share
              file chunks rather than large files. -In [Bittorrent](https://en.wikipedia.org/wiki/BitTorrent), each file chunk is hash identified so peers can
              _request and verify_ the chunk is a member of the larger,
              _content addressed_ file. +In [Bittorrent](https://en.wikipedia.org/wiki/BitTorrent), each file chunk is hash identified so peers can
              _request and verify_ the chunk is a member of the larger,
              _content addressed_ file. Notes: @@ -383,8 +383,8 @@ The properties of hash functions allow other kinds of representations. ## Public Key Representation -Because hashes serve as unique representations of other data,
              that other data could include public keys.
              -A system can map a plurality of key sizes to a fixed length
              (e.g. for use as a database key). +Because hashes serve as unique representations of other data,
              that other data could include public keys.
              +A system can map a plurality of key sizes to a fixed length
              (e.g. for use as a database key). For example, the ECDSA public key is 33 bytes: @@ -401,7 +401,7 @@ Hash of pub key: ## Commitment Schemes -It is often useful to commit to some information
              without storing or revealing it: +It is often useful to commit to some information
              without storing or revealing it: - A prediction market would want to reveal predictions only after the confirming/refuting event occurred. - Users of a system may want to discuss proposals without storing the proposal on the system. @@ -419,7 +419,7 @@ However, participants should not be able to modify their predictions or proposal -It is normal to add some randomness to the message
              to expand the input set size: +It is normal to add some randomness to the message
              to expand the input set size: $$ hash(message + randomness) => commitment $$ @@ -462,7 +462,7 @@ For now, just a brief introduction. Pointer-based linked lists are a foundation of programming. -But pointers are independent from the data they reference,
              so the data can be modified while maintaining the list. +But pointers are independent from the data they reference,
              so the data can be modified while maintaining the list. That is, pointer-based linked lists are not tamper evident. @@ -472,7 +472,7 @@ That is, pointer-based linked lists are not tamper evident. ## Hash-Based Linked Lists -Hash-based lists make the reference related to the data they are referencing.
              +Hash-based lists make the reference related to the data they are referencing.
              The properties of hash functions make them a good choice for this application. Any change at any point in the list would create downstream changes to all hashes. @@ -491,7 +491,7 @@ Each leaf is the hash of some data object and each node is the hash of its child ## Proofs -Merkle trees allow many proofs relevant to the rest of this course,
              e.g. that some data object is a member of the tree
              without passing the entire tree. +Merkle trees allow many proofs relevant to the rest of this course,
              e.g. that some data object is a member of the tree
              without passing the entire tree. **_More info in the next lesson._** @@ -513,13 +513,13 @@ Sr25519 hashes the message as part of its signing process. **Transactions** -In transactions in Substrate, key holders sign a
              _hash of the instructions_ when the instructions
              are longer than 256 bytes. +In transactions in Substrate, key holders sign a
              _hash of the instructions_ when the instructions
              are longer than 256 bytes. --- ## Database Keys -**TwoX64** is safe to use when users (read: attackers)
              cannot control the input, e.g. when a
              database key is a system-assigned index. +**TwoX64** is safe to use when users (read: attackers)
              cannot control the input, e.g. when a
              database key is a system-assigned index. **Blake2** should be used for everything else. diff --git a/content/cryptography/in-context/slides.md b/content/cryptography/in-context/slides.md index 7c7f8b4..6a6daa3 100644 --- a/content/cryptography/in-context/slides.md +++ b/content/cryptography/in-context/slides.md @@ -66,7 +66,7 @@ A side channel attack is when a cryptographic system is attacked, and the attack ## Timing Attacks -A timing attack can be possible if any of the following
              depend on the contents of a secret: +A timing attack can be possible if any of the following
              depend on the contents of a secret: @@ -180,7 +180,6 @@ NOTES provide such a function (e.g., NetBSD's consttime_memequal()), but no such function is specified in POSIX. On Linux, it may be necessary to implement such a function oneself. - ``` --- diff --git a/content/cryptography/intro/slides.md b/content/cryptography/intro/slides.md index 695121b..c70476d 100644 --- a/content/cryptography/intro/slides.md +++ b/content/cryptography/intro/slides.md @@ -88,7 +88,7 @@ not just person-to-person messages. _Cryptography based on public systems is more sound._ -**Kerckhoff's Principle:** Security should not rely on secret _methods_,
              but rather on secret _information_. +**Kerckhoff's Principle:** Security should not rely on secret _methods_,
              but rather on secret _information_. Notes: @@ -131,7 +131,7 @@ Do note the assumptions and monitor their validity over time (like quantum tech)
              -
              +
              Cryptography alone cannot make strong guarantees that data is available to people when they want to access it. @@ -144,9 +144,9 @@ We will touch on erasure coding, which makes data availability more efficient. ## Data Confidentiality -A party may gain access to information
              if and only if they know some secret (a key). +A party may gain access to information
              if and only if they know some secret (a key). -
              +
              Confidentiality ensures that a third party cannot read my confidential data. @@ -176,7 +176,7 @@ Suppose Alice and Bob are sending confidential messages back and forth. There ar Users can have the **credible** expectation that the stated origin of a message is authentic. -
              +
              Authenticity ensures that a third party cannot pretend I created some data. @@ -191,7 +191,7 @@ Notes: If data is tampered with, it is detectable. In other words, it possible to check if the current state of some data is the consistent with when it was created. -
              +
              Integrity ensures that if data I create is corrupted, it can be detected. @@ -199,7 +199,7 @@ Integrity ensures that if data I create is corrupted, it can be detected. ## Physical Signatures -Physical signatures provide weak authenticity guarantees
              (i.e. they are quite easy to forge), and no integrity guarantees. +Physical signatures provide weak authenticity guarantees
              (i.e. they are quite easy to forge), and no integrity guarantees. ---v @@ -218,7 +218,7 @@ Digital signatures provide a guarantee that the signed information has not been The sender of a message cannot deny that they sent it. -
              +
              Non-repudiation ensures if Bob sends me some data, I can prove to a third party that they sent it. @@ -226,7 +226,7 @@ Non-repudiation ensures if Bob sends me some data, I can prove to a third party ## One-Way Functions -One-way functions form the basis of both
              **(cryptographic) hashing** and **asymmetric cryptography**. A function $f$ is one way if: +One-way functions form the basis of both
              **(cryptographic) hashing** and **asymmetric cryptography**. A function $f$ is one way if: - it is reasonably fast to compute - it is very, very slow to undo @@ -260,7 +260,7 @@ Hashes can be useful for many applications: -- Representation of larger data object
              (history, commitment, file) +- Representation of larger data object
              (history, commitment, file) - Keys in a database - Digital signatures - Key derivation @@ -272,7 +272,7 @@ Hashes can be useful for many applications: ## Symmetric Cryptography -Symmetric encryption assumes all parties begin with some shared secret information, a potentially very difficult requirement.
              The shared secret can then be used to protect further communications from others who do not know this secret. +Symmetric encryption assumes all parties begin with some shared secret information, a potentially very difficult requirement.
              The shared secret can then be used to protect further communications from others who do not know this secret. In essence, it gives a way of _extending_ a shared secret over time. @@ -316,15 +316,15 @@ _Using only the public key_, information can be transformed ("encrypted") such t - Digital signatures provide message authenticity and integrity guarantees. -- _There are two lessons are dedicated to digital signatures,
              this is strictly an intro._ +- _There are two lessons are dedicated to digital signatures,
              this is strictly an intro._ --- ## Digital Signatures -**Signing function**: a function which operates on some
              _message data_ and some _secret_ to yield a _signature_. +**Signing function**: a function which operates on some
              _message data_ and some _secret_ to yield a _signature_. -A **signature** _proves_ that the signer had knowledge of the secret,
              without revealing the secret itself. +A **signature** _proves_ that the signer had knowledge of the secret,
              without revealing the secret itself. The signature cannot be used to create other signatures, and is unique to the message. @@ -343,9 +343,9 @@ It has a special property: it proves (beyond reasonable doubt) that the signer ( There is cryptographic proof that the secret was known to the producer of the signature. -
              +
              -The signer cannot claim that the signature was forged, unless they can defend a claim that the secret was compromised prior to signing.
              +The signer cannot claim that the signature was forged, unless they can defend a claim that the secret was compromised prior to signing.
              --- diff --git a/content/economics/basics/slides.md b/content/economics/basics/slides.md index 8293e65..a075b7b 100644 --- a/content/economics/basics/slides.md +++ b/content/economics/basics/slides.md @@ -71,7 +71,7 @@ Notes: --- -## Why are economic concepts
              important? +## Why are economic concepts
              important? @@ -119,7 +119,7 @@ Notes: ## Guiding Human Behavior -> An incentive is a bullet, a key:
              an often tiny object with astonishing power to change a situation.
              -- Steven Levitt -- +> An incentive is a bullet, a key:
              an often tiny object with astonishing power to change a situation.
              -- Steven Levitt -- Notes: @@ -311,8 +311,8 @@ Notes:
                -
              • A common model to help predict and rationalize the price
                which emerges from a market.
              • -
              • Can be used to (gu)estimate the quantity
                of produced goods vs. their market prices.
              • +
              • A common model to help predict and rationalize the price
                which emerges from a market.
              • +
              • Can be used to (gu)estimate the quantity
                of produced goods vs. their market prices.
              @@ -608,7 +608,7 @@ Notes: #### _(or: why bother trading at all?)_ -> It is the maxim of every prudent master of a family, never to attempt to make at home what it will cost him more to make than to buy.
              -- Adam Smith, 1776 -- +> It is the maxim of every prudent master of a family, never to attempt to make at home what it will cost him more to make than to buy.
              -- Adam Smith, 1776 -- Notes: @@ -749,7 +749,7 @@ Notes:
              • Money now is worth more than the same amount in the future.
              • Why? -
                  +
                  • Again, opportunity costs: The money at hand now could be invested, potentially earning more money.
                  • This potential earning capacity bestows more value to present money over future money.
                  @@ -866,7 +866,7 @@ Notes: ## Behavioral Economics -> Simply put, the stock market is a creation of man and therefore reflects human idiosyncrasy.
                  -- Ralph Nelson Elliott -- +> Simply put, the stock market is a creation of man and therefore reflects human idiosyncrasy.
                  -- Ralph Nelson Elliott -- --- diff --git a/content/economics/collective-decision-making/slides.md b/content/economics/collective-decision-making/slides.md index d276bd2..de22c7a 100644 --- a/content/economics/collective-decision-making/slides.md +++ b/content/economics/collective-decision-making/slides.md @@ -14,7 +14,7 @@ duration: 1 hour -##### Decision
                  making systems +##### Decision
                  making systems - Common systems - Goals and trade-offs @@ -46,7 +46,7 @@ Notes: ## Collective decision making -An umbrella term that contains voting mechanisms,
                  governance processes, policy making, budget allocation. +An umbrella term that contains voting mechanisms,
                  governance processes, policy making, budget allocation. --- @@ -90,10 +90,10 @@ Notes: ## A more profound interpretation -Long you live and high you fly
                  -Smiles you'll give and tears you'll cry
                  -**And all you touch and all you see
                  -Is all your life will ever be**
                  +Long you live and high you fly
                  +Smiles you'll give and tears you'll cry
                  +**And all you touch and all you see
                  +Is all your life will ever be**
                  -- Pink Floyd (Breathe) @@ -120,12 +120,12 @@ Notes: ## Goals -| | | -| :--------------: | :------------------------------------------------------------------------------------------: | -| **Utility** | - decision maximizes society's welfare
                  - it reflects people's preferences | -| **Legitimacy** | - decision is considered fair
                  - people trust the process | -| **Practicality** | - process is fast
                  - it is simple to understand | -| | | +| | | +| :--------------: | :-----------------------------------------------------------------------------: | +| **Utility** | - decision maximizes society's welfare
                  - it reflects people's preferences | +| **Legitimacy** | - decision is considered fair
                  - people trust the process | +| **Practicality** | - process is fast
                  - it is simple to understand | +| | | Notes: @@ -234,7 +234,7 @@ Notes: -- Not very practical:
                  asking everyone to vote. +- Not very practical:
                  asking everyone to vote. - One decision at a time. - Not great for emergencies. @@ -441,7 +441,7 @@ Notes: - A dictatorship system is captured by definition. -- A majority vote can lead to capture
                  if the minority's opinion is consistently ignored.
                  +- A majority vote can lead to capture
                  if the minority's opinion is consistently ignored.
                  Known as "tyranny of the majority". - It can affect legitimacy. @@ -457,7 +457,7 @@ Notes: ## Random dictator -Whenever there is a decision to be made,
                  pick a person at random in the collective
                  and let them decide as a dictator. +Whenever there is a decision to be made,
                  pick a person at random in the collective
                  and let them decide as a dictator. Notes: @@ -834,7 +834,7 @@ Notes: | 7 voters | C | B | A | | 5 voters | B | C | A | -
                  +
                  16 points for A, **25 points for B**, 19 points for C. diff --git a/content/economics/game-theory/slides.md b/content/economics/game-theory/slides.md index 6b2f59b..b7bc0db 100644 --- a/content/economics/game-theory/slides.md +++ b/content/economics/game-theory/slides.md @@ -172,7 +172,7 @@ Notes:
                  -##### Price-competition
                  between firms +##### Price-competition
                  between firms - Actions: Price charged. - Outcome: Demand for each firm, profit of each firm. @@ -249,23 +249,23 @@ Notes: ### Quiz Questions: -1. Is this game static or dynamic? - What would need to change in the description of the game such that it would fall in the other category? -1. Is this game of complete or incomplete information? - What would need to change in the description of the game such that it would fall in the other category? +1. Is this game static or dynamic? + What would need to change in the description of the game such that it would fall in the other category? +1. Is this game of complete or incomplete information? + What would need to change in the description of the game such that it would fall in the other category?
                  Notes: -1. The game is static. - For it to be dynamic, firms would need to make offers sequentially, _knowing what the firms before had offered_. +1. The game is static. + For it to be dynamic, firms would need to make offers sequentially, _knowing what the firms before had offered_. -2. The game is of complete information. - To make information incomplete, we would need to have that the value of hiring the engineer differs between firms and is unknown between firms. - Or that the cost of working for the engineer is not known to the firms. - The point is that we need to have uncertainty over payoffs. +2. The game is of complete information. + To make information incomplete, we would need to have that the value of hiring the engineer differs between firms and is unknown between firms. + Or that the cost of working for the engineer is not known to the firms. + The point is that we need to have uncertainty over payoffs. - This lesson focuses on static games of complete information. - When we look at auctions in lesson Price finding mechanisms, we will also consider games of incomplete information, both dynamic and static. @@ -543,7 +543,7 @@ However, a Nash equilibrium is a weaker notion than a dominant strategy, because
                • Sometimes people switch between equilibria (if they are made to)...
                -
                +

                Sweden, 1967.

                diff --git a/content/economics/price-finding-mechanisms/slides.md b/content/economics/price-finding-mechanisms/slides.md index c5f57ef..641c4e2 100644 --- a/content/economics/price-finding-mechanisms/slides.md +++ b/content/economics/price-finding-mechanisms/slides.md @@ -83,7 +83,7 @@ Notes: - Selena wants to sell one item of a good. - Two buyers, Alice and Bob. -- Each buyer has a secret _valuation_ $v_A$ and $v_B$:
                +- Each buyer has a secret _valuation_ $v_A$ and $v_B$:
                how much they are willing to pay for the item. @@ -112,7 +112,7 @@ Notes: - We saw the notion of an abstraction already in game theory class: we lose a bit in realism, but gain in structure which allows us to make precise statements, and develop a richer theory. The intuition and conclusions still apply in real life. - In particular, we are assuming that each of the three characters has a certain amount of information about the valuations of the other players, namely the distribution they are sampled from, and they can use this info to strategize their actions. -- Assuming that each valuation $v_i$ follows a uniform distribution between 0 and 1 simplifies Selena's life, because she knows that for any value $x\in [0,1]$, the probability that a bidder's valuation is below $x$ is exactly $x$, i.e., $P[v_i\leq x]=x$. +- Assuming that each valuation $v_i$ follows a uniform distribution between 0 and 1 simplifies Selena's life, because she knows that for any value $x\in \[0,1\]$, the probability that a bidder's valuation is below $x$ is exactly $x$, i.e., $P\[v_i\leq x\]=x$. - However, assuming a uniform distribution is just for pedagogical reasons: most results in auction theory can be extended to more general distributions. --- @@ -316,7 +316,7 @@ TIP: use arrow chars in unicode for style: - and pay the price at which the second-to-last
                bidder left. +- If you are the last one in the auction you win
                + and pay the price at which the second-to-last
                bidder left. @@ -495,9 +495,9 @@ Notes: - Assume you are Alice, with valuation $v_A$ and bid $b_A$. - Assuming that Bob's bid $b_B$ equals half his valuation $v_B$, that $v_B$ is sampled uniformly at random between 0 and 1, and that your bid $b_A$ is at most $1/2$, your winning probability is: \begin{align} - Pr[winning] &= Pr[b_B\leq b_A] \\ - &= Pr[v_B/2 \leq b_A] \\ - &= Pr[v_B \leq 2b_A] \\ + Pr\[winning\] &= Pr\[b_B\leq b_A\] \\ + &= Pr\[v_B/2 \leq b_A\] \\ + &= Pr\[v_B \leq 2b_A\] \\ &= 2b_A. \end{align} - Your profit in case of winning is $(v_A-b_A)$, hence your expected profit is $2b_A(v_A-b_A)$. @@ -524,7 +524,7 @@ Notes: The optimal strategies are so different, but somehow the fact that you underbid is exactly compensated by the fact that you pay more when you win. - Is there a deeper connection going on here? Or is it just a coincidence that the expected revenues are all the same so far? -- Formal proof of the expected revenue: recall that the valuations $v_A$ and $v_B$ are assumed to be independent variables uniformly drawn from $[0,1]$. +- Formal proof of the expected revenue: recall that the valuations $v_A$ and $v_B$ are assumed to be independent variables uniformly drawn from $\[0,1\]$. - The cumulative density function (CDF) of the higher valuation, $\max\{v_A, v_B\}$, is $F(x)=x^2$. This is because $F(x)$ is lower than $x$ only if both valuations are below $x$, and these are two independent events each happening with probability $x$. - Then, the probability density function (PDF) is $f(x)=F'(x)=2x$. @@ -552,7 +552,7 @@ Notes: - Selena continually lowers the price. -- As soon as a bidder accepts the price,
                +- As soon as a bidder accepts the price,
                they are declared winners and auction is over. - Winner pays the price they accepted. @@ -753,7 +753,7 @@ Notes: ## Sniping -_Answer:_ **candle auctions.**
                +_Answer:_ **candle auctions.**
                Dynamic first-price auction with _random ending time._ @@ -762,7 +762,7 @@ Dynamic first-price auction with _random ending time._ ## Sniping -_Answer:_ **candle auctions.**
                +_Answer:_ **candle auctions.**
                Dynamic first-price auction with _random ending time._ - Similar to first-price auction @@ -864,7 +864,7 @@ Link will be distributed! ## Further Reading -Polkadot & Kusama Auctions
                Data & Background information: +Polkadot & Kusama Auctions
                Data & Background information: diff --git a/content/formal-methods/intro/slides.md b/content/formal-methods/intro/slides.md index a98ce27..a3532e2 100644 --- a/content/formal-methods/intro/slides.md +++ b/content/formal-methods/intro/slides.md @@ -44,7 +44,7 @@ Link to article: (https://www-users.cse.umn.edu/~arnold/disasters/ariane.html) ## Software Correctness is _very_ important -> Program testing can be used to show the presence of bugs,
                but never to show their absence! +> Program testing can be used to show the presence of bugs,
                but never to show their absence! > > --Edgard Dijkstra-- @@ -80,7 +80,7 @@ Notes: ## Formal Methods Today -From being theoretical research interests
                to delivering practical cost-effective tools +From being theoretical research interests
                to delivering practical cost-effective tools @@ -143,7 +143,7 @@ Note: Notes: -- [Great blog](https://web.archive.org/web/20230209000724/www.pl-enthusiast.net/2017/10/23/what-is-soundness-in-static-analysis/) that explains the trade-offs between soundness and tractability +- [Great blog](https://web.archive.org/web/20230209000724/www.pl-enthusiast.net/2017/10/23/what-is-soundness-in-static-analysis/) that explains the trade-offs between soundness and tractability --- @@ -522,8 +522,8 @@ impl<'a> Arbitrary<'a> for Rgb { > Verify [Fixed-width](https://github.com/paritytech/parity-scale-codec/blob/master/src/codec.rs) & [Compact](https://github.com/paritytech/parity-scale-codec/blob/master/src/compact.rs) Encoding for integer types in SCALE. -
                -
                +
                +
                **Open Ended properties!** @@ -544,8 +544,8 @@ Notes: # Less Bugs -
                -
                -
                +
                +
                +
                **_Questions_** diff --git a/content/frame/benchmarking-1/slides.md b/content/frame/benchmarking-1/slides.md index 7c00d98..0a97e4b 100644 --- a/content/frame/benchmarking-1/slides.md +++ b/content/frame/benchmarking-1/slides.md @@ -267,11 +267,12 @@ For each component and repeat: - We set number of steps to 3. - Vary one component at a time, select high value for the others. -| | Δx | Δy | Δy | Δz | Δz | max | -| --- | --- | --- | --- | --- | --- | --- | -| x | 1 | 2 | 2 | 2 | 2 | 2 | -| y | 5 | 0 | 2 | 5 | 5 | 5 | -| z | 10 | 10 | 10 | 0 | 5 | 10 | + +| | Δx | Δy | Δy | Δz | Δz | max | +| - | -- | -- | -- | -- | -- | --- | +| x | 1 | 2 | 2 | 2 | 2 | 2 | +| y | 5 | 0 | 2 | 5 | 5 | 5 | +| z | 10 | 10 | 10 | 0 | 5 | 10 | --- diff --git a/content/frame/benchmarking-2/slides.md b/content/frame/benchmarking-2/slides.md index 206c4b9..3217c7e 100644 --- a/content/frame/benchmarking-2/slides.md +++ b/content/frame/benchmarking-2/slides.md @@ -148,7 +148,7 @@ Let's now step away from concepts and talk about cold hard data. ### Common Runtime Data Size and Performance -
                +
                diff --git a/content/frame/construct-runtime/slides.md b/content/frame/construct-runtime/slides.md index a4d915c..65da243 100644 --- a/content/frame/construct-runtime/slides.md +++ b/content/frame/construct-runtime/slides.md @@ -475,6 +475,7 @@ MyMaxVoters::get(); - Often times, in your test, you want mimic the progression of an empty block. - De-nada! We can fake everything in tests 🤠 + ---v @@ -536,7 +537,6 @@ fn test() { ```` ``` - --- ## Additional Resources 😋 diff --git a/content/frame/migrations/slides.md b/content/frame/migrations/slides.md index 7ed948b..4916822 100644 --- a/content/frame/migrations/slides.md +++ b/content/frame/migrations/slides.md @@ -124,10 +124,10 @@ pub type FooValue = StorageValue<_, Foo>; ``` ```rust - // old - pub enum Foo { A(u32), B(u32) } - // new - pub enum Foo { A(u32), B(u32), C(u128) } +// old +pub enum Foo { A(u32), B(u32) } +// new +pub enum Foo { A(u32), B(u32), C(u128) } ``` - Extending an enum is even more interesting, because if you add the variant to the end, no migration is needed. @@ -182,7 +182,7 @@ pub type FooValue = StorageValue<_, u32>; pub type BarValue = StorageValue<_, u32>; ``` -- So far everything is changing the _value_ format.
                +- So far everything is changing the _value_ format.
                @@ -208,7 +208,7 @@ pub type FooValue = StorageValue<_, u32>; pub type I_can_NOW_BE_renamEd_hahAA = StorageValue<_, u32>; ``` -- Handy macro if you must rename a storage type.
                +- Handy macro if you must rename a storage type.
                - This does _not_ require a migration. @@ -357,7 +357,6 @@ impl Hooks> for Pallet { } } } - ``` Stores the version as u16 in [`twox(pallet_name) ++ twox(:__STORAGE_VERSION__:)`](https://github.com/paritytech-stg/polkadot-sdk/blob/c7c5fc7/substrate/frame/support/src/traits/metadata.rs#L163). diff --git a/content/frame/origin/slides.md b/content/frame/origin/slides.md index 7200b06..9314b0e 100644 --- a/content/frame/origin/slides.md +++ b/content/frame/origin/slides.md @@ -131,14 +131,14 @@ pub fn set_code(origin: OriginFor, code: Vec) -> DispatchResultWithPostIn Setting the timestamp of the block. ```rust - /// Set the current time. - #[pallet::call_index(0)] - #[pallet::weight((T::WeightInfo::set(), DispatchClass::Mandatory))] - pub fn set(origin: OriginFor, #[pallet::compact] now: T::Moment) -> DispatchResult { - ensure_none(origin)?; - // -- snip -- - } + /// Set the current time. + #[pallet::call_index(0)] + #[pallet::weight((T::WeightInfo::set(), DispatchClass::Mandatory))] + pub fn set(origin: OriginFor, #[pallet::compact] now: T::Moment) -> DispatchResult { + ensure_none(origin)?; + // -- snip -- } +} ``` `None` origin is not very straight forward. More details next... diff --git a/content/frame/storage/slides.md b/content/frame/storage/slides.md index 21f6600..937e16c 100644 --- a/content/frame/storage/slides.md +++ b/content/frame/storage/slides.md @@ -41,7 +41,7 @@ Today we will focus on the top two layers: Runtime Storage APIs and Storage Over ### Overlay Deep Dive -
                +
                @@ -56,12 +56,12 @@ The overlay stages changes to the underlying database. Runtime Memory -
                +
                Runtime Storage API
                -
                +
                @@ -72,12 +72,12 @@ The overlay stages changes to the underlying database.
                Overlay Change Set
                -
                +
                Memory / Database Interface
                -
                +
                @@ -113,12 +113,12 @@ The overlay stages changes to the underlying database.
                Database
                Runtime Memory
                -
                +
                Runtime Storage API
                -
                +
                @@ -129,12 +129,12 @@ The overlay stages changes to the underlying database.
                Overlay Change Set
                -
                +
                Memory / Database Interface
                -
                +
                @@ -151,7 +151,7 @@ The overlay stages changes to the underlying database. ### Overlay: Balance Transfer -
                +
                @@ -166,12 +166,12 @@ The overlay stages changes to the underlying database.
                Database
                Runtime Memory
                -
                +
                Runtime Storage API
                -
                +
                @@ -182,12 +182,12 @@ The overlay stages changes to the underlying database.
                Overlay Change Set
                -
                +
                Memory / Database Interface
                -
                +
                @@ -204,7 +204,7 @@ The overlay stages changes to the underlying database. ### Overlay: Balance Transfer -
                +
                @@ -220,12 +220,12 @@ The overlay stages changes to the underlying database.
                Database
                Runtime Memory
                -
                +
                Runtime Storage API
                -
                +
                @@ -236,12 +236,12 @@ The overlay stages changes to the underlying database.
                Overlay Change Set
                -
                +
                Memory / Database Interface
                -
                +
                @@ -258,7 +258,7 @@ The overlay stages changes to the underlying database. ### Overlay: Balance Transfer -
                +
                @@ -273,12 +273,12 @@ The overlay stages changes to the underlying database.
                Database
                Runtime Memory
                -
                +
                Runtime Storage API
                -
                +
                @@ -289,12 +289,12 @@ The overlay stages changes to the underlying database.
                Overlay Change Set
                -
                +
                Memory / Database Interface
                -
                +
                @@ -311,7 +311,7 @@ The overlay stages changes to the underlying database. ### Overlay: Implications -
                +
                @@ -326,12 +326,12 @@ The overlay stages changes to the underlying database.
                Database
                Runtime Memory
                -
                +
                Runtime Storage API
                -
                +
                @@ -342,12 +342,12 @@ The overlay stages changes to the underlying database.
                Overlay Change Set
                -
                +
                Memory / Database Interface
                -
                +
                @@ -368,7 +368,7 @@ also this means that cross implementation of substrate/polkadot can be tricky to ### Additional Storage Overlays (Transactional) -
                +
                @@ -384,12 +384,12 @@ also this means that cross implementation of substrate/polkadot can be tricky to
                Database
                Runtime Memory
                -
                +
                Runtime Storage API
                -
                +
                @@ -400,7 +400,7 @@ also this means that cross implementation of substrate/polkadot can be tricky to
                Transactional Layer
                -
                +
                @@ -411,12 +411,12 @@ also this means that cross implementation of substrate/polkadot can be tricky to
                Overlay Change Set
                -
                +
                Memory / Database Interface
                -
                +
                @@ -467,7 +467,7 @@ This is the same behavior as you would expect from smart contract environments l Transactional layers can be used to attack your chain: -
                +
                - Allow a user to spawn a lot of transactional layers. - On the top layer, make a bunch of changes. diff --git a/content/overview.md b/content/overview.md index 4a284a0..743f695 100644 --- a/content/overview.md +++ b/content/overview.md @@ -40,6 +40,8 @@ The academy uses _explicit terms_ to describe materials use within as _content c The course is segmented into **modules**, with the granular **lessons** intended to be completed in the sequence provided in the left-side navigation bar. + + | Module | Topic | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | [🔐 Cryptography](./cryptography/) | _Applied_ cryptography concepts and introduction to many common tools of the trade for web3 builders. | @@ -50,6 +52,8 @@ The course is segmented into **modules**, with the granular **lessons** intended | [🟣 Polkadot](./polkadot/) | The Polkadot blockchain covered in depth, focus on high-level design and practically how to utilize it's blockspace. | | [💱 XCM](./xcm/) | The cross consensus messaging format covered from first principals to use in protocols. | + + The lessons include materials used, with links and instructions to required external materials as needed.[^except] [^except]: _Notably, the graded assignments for the Academy and some solutions to public activities and exercises remain closed source, and links are intentionally left out of this book. These materials may be shared as needed with students in person during the Academy._ diff --git a/content/polkadot/async-backing-deep/slides.md b/content/polkadot/async-backing-deep/slides.md index ef79fff..98aa426 100644 --- a/content/polkadot/async-backing-deep/slides.md +++ b/content/polkadot/async-backing-deep/slides.md @@ -150,7 +150,6 @@ Notes: ## Constraints and Modifications ```rust - pub struct Constraints { /// The minimum relay-parent number accepted under these constraints. pub min_relay_parent_number: BlockNumber, @@ -201,7 +200,6 @@ pub struct ConstraintModifications { /// Whether a pending code upgrade has been applied. pub code_upgrade_applied: bool, } - ``` Notes: @@ -296,7 +294,6 @@ Out of scope: Excerpt from `backing_state()` in `runtime/parachains/src/runtime_api_impl/vstaging.rs` ```rust - let (ump_msg_count, ump_total_bytes) = >::relay_dispatch_queue_size(para_id); let ump_remaining = config.max_upward_queue_count - ump_msg_count; @@ -316,7 +313,6 @@ let constraints = Constraints { upgrade_restriction, future_validation_code, }; - ``` --- @@ -326,7 +322,6 @@ let constraints = Constraints { Excerpt from `Constraints::apply_modifications()` ```rust - if modifications.dmp_messages_processed > new.dmp_remaining_messages.len() { return Err(ModificationError::DmpMessagesUnderflow { messages_remaining: new.dmp_remaining_messages.len(), @@ -336,7 +331,6 @@ if modifications.dmp_messages_processed > new.dmp_remaining_messages.len() { new.dmp_remaining_messages = new.dmp_remaining_messages[modifications.dmp_messages_processed..].to_vec(); } - ``` --- @@ -346,14 +340,12 @@ if modifications.dmp_messages_processed > new.dmp_remaining_messages.len() { `Excerpt from Fragment::validate_against_constraints()` ```rust - if relay_parent.number < constraints.min_relay_parent_number { return Err(FragmentValidityError::RelayParentTooOld( constraints.min_relay_parent_number, relay_parent.number, )) } - ``` --- @@ -361,7 +353,6 @@ if relay_parent.number < constraints.min_relay_parent_number { ## AsyncBackingParams ```rust - pub struct AsyncBackingParams { /// The maximum number of para blocks between the para head in a relay parent /// and a new candidate. Restricts nodes from building arbitrary long chains @@ -375,7 +366,6 @@ pub struct AsyncBackingParams { /// When async backing is disabled, the only valid value is 0. pub allowed_ancestry_len: u32, } - ```
                @@ -418,7 +408,6 @@ Mention Function `request_backable_candidates` from the Provisioner subsystem ```rust - /// Requests backable candidates from Prospective Parachains subsystem /// based on core states. /// @@ -483,7 +472,6 @@ async fn request_backable_candidates( Ok(selected_candidates) } - ``` Notes: diff --git a/content/polkadot/async-backing-shallow/slides.md b/content/polkadot/async-backing-shallow/slides.md index f3546b1..d137719 100644 --- a/content/polkadot/async-backing-shallow/slides.md +++ b/content/polkadot/async-backing-shallow/slides.md @@ -22,12 +22,19 @@ Lets get to it - Synchronous vs asynchronous - Why is asynchronous backing desirable? + + - High level mechanisms of async backing + + - The unincluded segment, and prospective parachains + + - Async backing enabling other roadmap items + @@ -68,6 +75,7 @@ Our cache of parablock candidates allows us to pause just before that dividing l 1. "The best existing parablock I'm aware of will eventually be included in the relay chain." 1. "There won't be a chain reversion impacting that best parablock." + @@ -92,10 +100,15 @@ Brief BABE fork choice rule review 1. 3-5x more extrinsics per block 1. Shorter parachain block times 6s vs 12s + + 1. Resulting 6-10x boost in quantity of blockspace + + 1. Fewer wasted parachain blocks + @@ -174,10 +187,15 @@ Image version 3: - A parachain's record of all parablocks on a particular chain fork produced but not yet included - Used to apply limitations when constructing future blocks + + - Lives in the parachain runtime + + - Viewed from the perspective of a new parablock under construction + @@ -220,10 +238,15 @@ UsedBandwidth: - The relay chain's record of all candidates on all chain forks from all parachains - As if you folded all unincluded segments into one huge structure + + - Used to store candidates and later provide them to the on-chain backing process + + - Lives in the relay client (off chain) + diff --git a/content/polkadot/availability-cores/slides.md b/content/polkadot/availability-cores/slides.md index d4ee08b..211d9d3 100644 --- a/content/polkadot/availability-cores/slides.md +++ b/content/polkadot/availability-cores/slides.md @@ -40,13 +40,23 @@ Lets get to it - What do availability cores represent? + + + - How do cores map parachain leases and claims to validator subsets? + + - How do cores gate each step of the parachains protocol? + + - What advantages do cores give us now? + + - What roadmap items do cores accommodate? + @@ -55,7 +65,7 @@ Lets get to it ## Review, Blockspace -> Blockspace is the capacity of a blockchain
                to finalize and commit operations +> Blockspace is the capacity of a blockchain
                to finalize and commit operations Polkadot's primary product is _blockspace_. @@ -67,8 +77,12 @@ Polkadot blockspace is consumed in two ways: -1. When the relay chain validates, includes,
                and finalizes a parachain block -1. When the capacity to validate a parachain block
                is left unused and expires +1. When the relay chain validates, includes,
                and finalizes a parachain block + + + +1. When the capacity to validate a parachain block
                is left unused and expires +
                @@ -84,13 +98,23 @@ Polkadot blockspace is consumed in two ways: - Availability cores are the abstraction we use to allocate Polkadot's blockspace. + + + - Allocated via leases and on-demand claims + + - Cores divide blockspace supply into discrete units, 1 parachain block per relay chain block per core + + - Why "availability"? + + - Why "core"? + @@ -110,15 +134,18 @@ Notes: ## Availability -Though cores gate the entire parachain block pipeline,
                the availability process alone determines when these cores are considered occupied vs free. +Though cores gate the entire parachain block pipeline,
                the availability process alone determines when these cores are considered occupied vs free. To recap, the goals of availability are: 1. To ensure that approvers will always be able to recover the PoVs to validate their assigned blocks + + 2. To ensure that parachain nodes can recover blocks in the case that a parablock author fails to share them, through malintent or malfunction + --- @@ -164,16 +191,27 @@ Notes: 1. Block author places a candidate on-chain as backed, immediately occupying its scheduled core + + 1. Candidate backers distribute erasure coded PoV chunks + + 1. Validators distribute statements as to which candidates they have chunks for + + 1. Availability threshold is met (2/3 vs the 1/3 needed to reconstruct POV) + + 1. Candidate marked as included on chain and core freed + + 1. Approvers or parachain nodes retrieve PoV chunks as needed + @@ -259,10 +297,15 @@ Notes: - Randomness via schnorrkel::vrf - Approver assignments activated with delay tranches until threshold met + + - Results in 30-40 approvers checking each block + + - Different assignments each block prevent DOS + @@ -405,8 +448,11 @@ if Some(candidate.descriptor().para_id) != rp_state.assignment { - For each core that is either unoccupied or is about to be a new candidate is found - A candidate for the parachain scheduled next on that core is provided to the block author + + - Backed on-chain -> immediately occupies core + @@ -483,6 +529,7 @@ Approvals, Disputes, and Finality are only provided to included candidates 1. Predictability of parachain execution 1. Predictability of allocation for execution sharding + @@ -509,8 +556,11 @@ Notes: - Multiple cores per parachain - Overlapping leases of many lengths + + - Lease + On-demand + @@ -529,7 +579,7 @@ Notes: ## Divisible and Marketable Blockspace -We want Parachains to buy, sell, and split blockspace such that they are allocated exactly as much as fits their needs.

                +We want Parachains to buy, sell, and split blockspace such that they are allocated exactly as much as fits their needs.

                diff --git a/content/polkadot/blockspace/slides.md b/content/polkadot/blockspace/slides.md index 1f5b31f..50aae9a 100644 --- a/content/polkadot/blockspace/slides.md +++ b/content/polkadot/blockspace/slides.md @@ -188,7 +188,7 @@ Spot instances may be more expensive if overall demand is high, but help to soot Within Polkadot, we measure the amount of blockspace that an application can use in _coretime_. -Just like a CPU and OS, there is a scheduler that multiplexes many
                different processes onto execution cores. +Just like a CPU and OS, there is a scheduler that multiplexes many
                different processes onto execution cores. Coretime is acquired through either primary or secondary marketplaces. diff --git a/content/polkadot/build-a-parachain/slides.md b/content/polkadot/build-a-parachain/slides.md index d5488b0..f25a8f2 100644 --- a/content/polkadot/build-a-parachain/slides.md +++ b/content/polkadot/build-a-parachain/slides.md @@ -133,10 +133,10 @@ If we actually include an infinite loop into the `validate_block` function, a pa - Our node will sync relay chain blocks -- When importing the new best block,
                we'll connect to the backing group -- Then we'll advertise our block ("collation")
                to a validator in the group -- The validator will request the collation
                from us using `collator-protocol` -- Now it's in the hands of validators
                to include our block +- When importing the new best block,
                we'll connect to the backing group +- Then we'll advertise our block ("collation")
                to a validator in the group +- The validator will request the collation
                from us using `collator-protocol` +- Now it's in the hands of validators
                to include our block diff --git a/content/polkadot/cumulus/slides.md b/content/polkadot/cumulus/slides.md index f22c267..f3d8812 100644 --- a/content/polkadot/cumulus/slides.md +++ b/content/polkadot/cumulus/slides.md @@ -18,14 +18,23 @@ Cumulus is the glue which attaches substrate based chains to Polkadot, convertin 1. What is Cumulus? 1. Cumulus and Para-Relay Communication + + 1. How Cumulus Keeps a Parachain Node Informed + + 1. Collation Generation and Advertisement + + 1. How Cumulus Collations Enable Parablock Validation + + 1. How Cumulus Enables Runtime Upgrades + @@ -84,10 +93,15 @@ Notes: - Follow relay "new best head" to update para "new best head" - Follow relay finalized block to update para finalized block + + - Request parablocks not shared by peers from relay (data recovery) + + - Collation generation and announcement + Notes: @@ -115,7 +129,7 @@ Notes: Before addressing collation generation let's first address the other three key Cumulus processes. These drive parachain consensus and ensure the availability of parachain blocks. -
                +
                Together they keep parachain nodes up to date such that collating is possible. Notes: @@ -184,7 +198,7 @@ Notes: To facilitate shared security, parachains inherit their finality from the relay chain. -
                +
                ```rust[|4-8] // Greatly simplified @@ -206,7 +220,7 @@ loop { ### Ensuring Block Availability As a part of the parachains protocol, Polkadot makes parachain blocks available for several hours after they are backed. -

                +

                @@ -261,10 +275,15 @@ Notes: - Erasure coding is applied to the PoV, breaking it into chunks - 3x original PoV size, vs 300x to store copies + + - 1/3 of chunks sufficient to assemble PoV + + - 2/3 of validators must claim to have their chunks + @@ -289,12 +308,19 @@ The last of our key processes 1. Relay node imports block in which parachain's avail. core was vacated 1. `CollationGeneration` requests a collation from the collator + + 1. Parachain consensus decides whether this collator can author + + 1. Collator proposes, seals, and imports a new block + + 1. Collator bundles the new block and information necessary to process and validate it, a **collation!** +
                @@ -382,7 +408,7 @@ pub struct Pvf { } ``` -
                +
                - New state transitions that occur on a parachain must be validated against the PVF @@ -404,11 +430,11 @@ The code is hashed and saved in the storage of the relay chain. - The PVF is not just a copy paste of the parachain Runtime -
                +
                - The PVF contains an extra function, `validate_block` -
                +
                **WHY!?** @@ -444,12 +470,19 @@ The input of the runtime validation process is the PoV and the function called i - The parachain runtime expects to run in conjunction with a parachain client - But validation is occurring in a relay chain node + + - We need to implement the API the parachain client exposes to the runtime, known as host functions + + - The host functions most importantly allow the runtime to query its state, so we need a light weight replacement for the parachain's state sufficient for the execution of this single block + + - `validate_block` prepares said state and host functions +
                @@ -476,7 +509,7 @@ fn validate_block(input: InputParams) -> Output { } ``` -
                +
                > But where does `storage_proof` come from? @@ -532,8 +565,11 @@ Code highlighting: - Acts as a replacement for the parachain's pre-state for the purpose of validating a single block - It allows the reconstruction of a sparse in-memory merkle trie + + - State root can then be compared to that from parent header + --- @@ -547,11 +583,14 @@ Code highlighting: -
                +
                - Only includes the data modified in this block along with hashes of the data from the rest of the trie + + - This makes up the majority of the data in a collation (max 5MiB) + Notes: @@ -586,8 +625,11 @@ fn validate_block(input: InputParams) -> Output { - Now we know where the **storage_proof** comes from! - **into_state** constructs our storage trie + + - Host functions written to access this new storage + --- @@ -597,6 +639,7 @@ fn validate_block(input: InputParams) -> Output { - Every Substrate blockchain supports runtime upgrades + ##### Problem @@ -624,7 +667,7 @@ The relay chain needs a fairly hard guarantee that PVFs can be compiled within a -
                +
                - Collators execute a runtime upgrade but it is not applied - Collators send the new runtime code to the relay chain in a collation @@ -651,8 +694,11 @@ Notes: - binary vote: accept or reject - Super majority concludes the vote + + - The state of the new PVF is updated on the relay chain + Notes: diff --git a/content/polkadot/data-sharding/slides.md b/content/polkadot/data-sharding/slides.md index 20f90de..a232d87 100644 --- a/content/polkadot/data-sharding/slides.md +++ b/content/polkadot/data-sharding/slides.md @@ -91,7 +91,6 @@ The goal: ### In code ```rust - type Data = Vec; pub struct Chunk { @@ -189,7 +188,7 @@ How do we do reconstruction? - Each PoV is divided into $N_{validator}$ chunks - Validator with index i gets a chunk with the same index - Validators sign statements when they receive their chunk -- Once we have $\frac{2}{3} + 1$ of signed statements,
                PoV is considered available +- Once we have $\frac{2}{3} + 1$ of signed statements,
                PoV is considered available - Any subset of $\frac{1}{3} + 1$ of chunks can recover the data
                @@ -255,7 +254,7 @@ This can eliminate honest majority assumption! This approach guarantees there's at least one honest full nodes that has the data with high probability. -
                +
                > @@ -304,7 +303,7 @@ Danksharding is aiming at 1.3 MB/s and Celestia < 1 MB/s. -- Data Availability Sampling for parachain
                light clients and full nodes +- Data Availability Sampling for parachain
                light clients and full nodes - Consider using KZG commitments - Reducing the number of signatures to verify - A Data Availability Parachain diff --git a/content/polkadot/decisions/slides.md b/content/polkadot/decisions/slides.md index 1650900..eb5b7e3 100644 --- a/content/polkadot/decisions/slides.md +++ b/content/polkadot/decisions/slides.md @@ -20,19 +20,19 @@ Jeff Bezos outlined in an annual letter to Amazon shareholders how he approaches Notes: - + --- ## Type 1 Decisions -> Some decisions are consequential and irreversible or nearly irreversible – **one-way doors** – and these decisions must be made methodically, carefully, slowly, with great deliberation and consultation. If you walk through and don't like what you see on the other side, you can't get back to where you were before. We can call these Type 1 decisions. +> Some decisions are consequential and irreversible or nearly irreversible – **one-way doors** – and these decisions must be made methodically, carefully, slowly, with great deliberation and consultation. If you walk through and don't like what you see on the other side, you can't get back to where you were before. We can call these Type 1 decisions. --- ## Type 2 Decisions -> But most decisions aren't like that – they are changeable, reversible – **they're two-way doors**. If you've made a suboptimal Type 2 decision, you don't have to live with the consequences for that long. You can reopen the door and go back through. Type 2 decisions can and should be made quickly by high judgment individuals or small groups. +> But most decisions aren't like that – they are changeable, reversible – **they're two-way doors**. If you've made a suboptimal Type 2 decision, you don't have to live with the consequences for that long. You can reopen the door and go back through. Type 2 decisions can and should be made quickly by high judgment individuals or small groups. --- diff --git a/content/polkadot/execution-sharding/slides.md b/content/polkadot/execution-sharding/slides.md index 213f8a2..f66806d 100644 --- a/content/polkadot/execution-sharding/slides.md +++ b/content/polkadot/execution-sharding/slides.md @@ -112,14 +112,14 @@ Goal: Have as few checkers as reasonably possible. Notes: -Every Session (4 hours), validators are _partitioned_ into small **groups** which work together.
                +Every Session (4 hours), validators are _partitioned_ into small **groups** which work together.
                Groups are assigned to specific **Execution Core**s, and these assignments change every few blocks. --- ## Definition: Candidate -> A **Candidate** is a parachain block
                which has not yet been finalized in the relay chain. +> A **Candidate** is a parachain block
                which has not yet been finalized in the relay chain. --- @@ -318,7 +318,7 @@ To fulfill this goal we need 2 things. 1. A protocol for proving validity of included candidates -1. Consensus rules for the relay chain
                to avoid building on or finalizing
                relay chain forks containing bad candidates. +1. Consensus rules for the relay chain
                to avoid building on or finalizing
                relay chain forks containing bad candidates.
                @@ -332,7 +332,7 @@ Checking involves three operations: 1. Recovering the data from the network (by fetching chunks) 1. Executing the parablock, checking success -1. Check that outputs match the ones posted
                to the relay chain by backers +1. Check that outputs match the ones posted
                to the relay chain by backers
                @@ -496,7 +496,7 @@ This causes a "reorganization" whenever a dispute resolves against a candidate. -> How are complex off-chain systems
                implemented using Substrate? +> How are complex off-chain systems
                implemented using Substrate? --- diff --git a/content/polkadot/fellowship/slides.md b/content/polkadot/fellowship/slides.md index 405e9d2..6383e94 100644 --- a/content/polkadot/fellowship/slides.md +++ b/content/polkadot/fellowship/slides.md @@ -19,8 +19,11 @@ duration: 30 mins #### 1. Technical 🔐 - Can the software be executed in a decentralized manner? + + - Can multiple nodes actually run the software and come to consensus? + Notes: @@ -39,6 +42,7 @@ Notes: - Intermediaries, gateways, pools. - Is the right "software" being executed by node operators? + Notes: @@ -58,10 +62,15 @@ Notes: #### 3. Intellectual 🧠 - How many people know the existing protocol well enough to understand it. + + - Which subset of these people make decisions about the future? + + - Important to remember that node operators are usually in neither. + Notes: @@ -131,14 +140,23 @@ around it and letting it be as-is, but it might be sub-optimal. ## The Fellowship Lifecycle 1. Initial seed + + 1. Entry + + 1. Promotion + + 1. Continuation + + 1. Gradual demote every 3-6 months. + ---v @@ -254,7 +272,7 @@ The manifesto provides one such example - The (potentially) softest of the materials - Wide range of hardness (1-3 Moh) -- Shares the exact same chemical composition as the material of the highest rank Grand Master—the hardest material—symbolising the individual’s potential to go all the +- Shares the exact same chemical composition as the material of the highest rank Grand Master—the hardest material—symbolizing the individual’s potential to go all the way. ---v diff --git a/content/polkadot/intro/slides.md b/content/polkadot/intro/slides.md index 8d55f65..f715ff4 100644 --- a/content/polkadot/intro/slides.md +++ b/content/polkadot/intro/slides.md @@ -57,7 +57,7 @@ Polkadot fulfills its goals with a combination of mechanisms and games which pro Notes: -source: banner image from +source: banner image from --- @@ -99,7 +99,7 @@ It aims to do so at high scale. > (3) Explicit network-wide governance and co-evolution -Polkadot stakeholders explicitly govern and evolve the network,
                with the ability to set new rules. +Polkadot stakeholders explicitly govern and evolve the network,
                with the ability to set new rules. --- @@ -143,7 +143,7 @@ Validators are _incentivized_ to do things like put user transactions in blocks Validators are strongly punished for explicitly doing their job wrongly. -The games work as long as enough validators are doing their job
                and also not misbehaving. +The games work as long as enough validators are doing their job
                and also not misbehaving. --- @@ -188,7 +188,7 @@ Simplified Polkadot Architecture (Parachains) The relay chain is the "hub" of Polkadot, providing the main games which validators play. It is built with Substrate. -Notably, the functionality of the relay chain is minimized,
                with the expectation that more complex functionalities will be pushed to less critical parts of the system. +Notably, the functionality of the relay chain is minimized,
                with the expectation that more complex functionalities will be pushed to less critical parts of the system. --- @@ -198,7 +198,7 @@ Notably, the functionality of the relay chain is minimized,
                with the expecta - Governance (moving to parachain) - Staking -- Registration, scheduling,
                and advancement of parachains +- Registration, scheduling,
                and advancement of parachains - Communication between parachains - Consensus Safety - Balance Transfers @@ -248,7 +248,7 @@ These games are the enablers of all activity within Polkadot. -
                +
                **The game works whenever <1/3 of validators misbehave.** @@ -279,7 +279,7 @@ These games are the enablers of all activity within Polkadot. -
                +
                **The game works whenever <1/3 of validators misbehave.** @@ -352,7 +352,7 @@ Notes: - Tokens are burned if they are not spent. -
                +
                The intention of the treasury is to pay people to help grow Polkadot itself. As tokens are burned, this creates pressure to fund public projects. @@ -478,7 +478,7 @@ Polkadot allocates its resources to parachains through **Execution Cores**. Just like a decentralized CPU, Polkadot multiplexes many processes across cores. -When a parachain is assigned to a core, it can advance.
                +When a parachain is assigned to a core, it can advance.
                Otherwise, it lies dormant. Execution Cores enable efficient allocation through _Coretime_ trading. @@ -507,7 +507,7 @@ Time --> ## Coretime: Polkadot's Product -Coretime is what applications buy to build on Polkadot.
                +Coretime is what applications buy to build on Polkadot.
                Goal: be like cloud. Primary and secondary markets are key enablers. diff --git a/content/polkadot/light-clients/slides.md b/content/polkadot/light-clients/slides.md index 920e814..9036a17 100644 --- a/content/polkadot/light-clients/slides.md +++ b/content/polkadot/light-clients/slides.md @@ -4,7 +4,7 @@ description: Light Clients and Unstoppable Apps, for web3 builders. duration: 45+ mins --- -# Light clients
                and
                Unstoppable Apps +# Light clients
                and
                Unstoppable Apps --- @@ -399,7 +399,7 @@ A Light client receives these justifications and this way it verifies the authen ready - +
                Only verifies the authenticity of blocks
                Requests state of the chain on demand
                No database whatsoever
                @@ -504,10 +504,10 @@ Notes: Substrate_connect --> PolkadotJS_API PolkadotJS_API --> UI_dAPP - Smoldot_Light_Client --> Custom_Code\n(with_JSON_RPC_API) - Custom_Code\n(with_JSON_RPC_API) --> UI_dAPP + Smoldot_Light_Client --> Custom_Code\n(with_JSON_RPC_API) + Custom_Code\n(with_JSON_RPC_API) --> UI_dAPP - + --- @@ -515,8 +515,11 @@ Notes: ## Smoldot Light Client - (As Substrate, it also) supports the new JSON-RPC protocol that has been developed; + + - Light and fast enough so that it can be embedded into a mobile application or an application in general; + Notes: @@ -540,8 +543,11 @@ The dApp (UI) connects to a third-party-owned publicly-accessible node client ## So what one needs to do - Find the web-socket url of a 3rd party node (JSON-RPC node) that one trusts; + + - Add it to the code and use it; + ---v @@ -575,15 +581,23 @@ The dApp (UI) connects to a node client that the user has installed on their mac -1. Install dependencies
                -(e.g. rust, openssl, cmake, llvm etc); +1. Install dependencies
                + (e.g. rust, openssl, cmake, llvm etc); + + 1. Clone from github the "polkadot" repo; + + 1. Build the node locally; + + 1. Start the node locally; + + 1. Wait for the node to synchronize; @@ -747,12 +761,19 @@ console.log('Please visit: https://cloudflare-ipfs.com/ipns/dotapps.io/?rpc=ws%3 #### Known vulnerabilities - Eclipse attacks (Full node & Light client) + + - Long-range attacks (Full node & Light client) + + - Invalid best block (Only Light client) + + - Finality stalls (Mostly Light client) + Notes: diff --git a/content/polkadot/npos/slides.md b/content/polkadot/npos/slides.md index dddf4f1..a80aa7f 100644 --- a/content/polkadot/npos/slides.md +++ b/content/polkadot/npos/slides.md @@ -145,10 +145,15 @@ Same issue as before. ### What is NPoS: Re-inventing the Wheel - ✅ As a nominator, you are free to express your desire to back non-winners as well. Once enough people have expressed the same desire, the non-winner will become a winner. + + - ✅ Has a much higher chance to make sure staked tokens won't get wasted. + + - ✅ Can optimize other criteria other than "who had more approval votes". + --- @@ -226,10 +231,15 @@ Same issue as before. - Let's first recap: 1. Polkadot validators are the source of truth for the state transition of both the relay chain and all of the parachains + bridges. + + 2. Polkadot validator are assigned to parachains as backing group, and swapped over time. + + 3. Polkadot validators all author the same number of blocks, i.e. they are of same importance. + Notes: @@ -275,8 +285,7 @@ A common example: we allow signed submissions. What if they send solutions that ### NPoS Objective: Election Score -- The default algorithm used in both the onchain/offchain solvers is the [Phragmen - algorithm](https://en.wikipedia.org/wiki/Phragmen%27s_voting_rules). +- The default algorithm used in both the onchain/offchain solvers is the [Phragmen algorithm](https://en.wikipedia.org/wiki/Phragmen%27s_voting_rules). - Proved to provide high fairness and justified representation properties whilst being verifiable in linear time. diff --git a/content/polkadot/opengov/slides.md b/content/polkadot/opengov/slides.md index 1a3b484..87435f4 100644 --- a/content/polkadot/opengov/slides.md +++ b/content/polkadot/opengov/slides.md @@ -297,7 +297,7 @@ Steps in order: **Proposing, Lead In, Deciding, Confirming, Enactment** - Addressed with time varying curves - Support threshold - Starts at ~50% - - Ends at minimum secure turnout for track
                (EX: Big Spender ends at 0 + epsilon %) + - Ends at minimum secure turnout for track
                (EX: Big Spender ends at 0 + epsilon %) - Approval threshold - Starts at 100% - Ends at 50 + epsilon % @@ -365,7 +365,7 @@ Solution: Some sort of oracle capable of providing expert information -## Enter...

                The Polkadot Fellowship +## Enter...

                The Polkadot Fellowship --- @@ -418,18 +418,31 @@ Stress that as an oracle, the Fellowship can't take any action on its own. Any w - Open source + single process + track abstraction -> Transparency + + - Liberal proposal creation + greater throughput + per-track delegation -> Accessibility + + - Accessibility + No special bodies -> Decentralization + + - Limited origins + emergency tracks + white list -> Security + + - Multiple tracks + low risk tracks -> Concurrency + + - Low risk tracks + early confirmation -> Speed + + - Support and approval threshold curves + white list -> Agility + @@ -438,7 +451,7 @@ Stress that as an oracle, the Fellowship can't take any action on its own. Any w -# OpenGov

                By The Numbers +# OpenGov

                By The Numbers --- @@ -487,7 +500,7 @@ Stress that as an oracle, the Fellowship can't take any action on its own. Any w 1. [PolkaWorld Hands-On OpenGov](https://polkaworld.medium.com/a-hands-on-guide-for-kusamas-open-gov-governance-system-98277629b0c5) 1. [OpenGov Article from Moonbeam Team](https://moonbeam.network/blog/opengov/) -1. [Gavin’s Polkadot Decoded 2022 talk](https://www.youtube.com/watch?v=EF93ZM_P_Oc) +1. [Gavin’s Polkadot Decoded 2022 talk](https://www.youtube.com/watch?v=EF93ZM_P_Oc) 1. [Gov V1 tracking](https://polkadot.polkassembly.io/) 1. [OpenGov tracking](https://kusama.subsquare.io/) diff --git a/content/polkadot/scaling-heterogeneous/slides.md b/content/polkadot/scaling-heterogeneous/slides.md index a910907..dbc1828 100644 --- a/content/polkadot/scaling-heterogeneous/slides.md +++ b/content/polkadot/scaling-heterogeneous/slides.md @@ -72,7 +72,7 @@ https://www.starknet.io/en/posts/developers/rollup-validium-volition-where-is-yo Notes: -- +- - --- @@ -164,7 +164,7 @@ Notes: Notes: -- +- --- diff --git a/content/polkadot/xcmp/slides.md b/content/polkadot/xcmp/slides.md index 048dd2e..0e8a68e 100644 --- a/content/polkadot/xcmp/slides.md +++ b/content/polkadot/xcmp/slides.md @@ -50,7 +50,7 @@ To do this, it adds additional limitations to candidates to ensure messaging rul XCMP is the data layer, while XCM is the language. -XCMP only focuses on the transmission of raw bytes between chains.
                +XCMP only focuses on the transmission of raw bytes between chains.
                In this lesson we will focus only on XCMP. @@ -217,7 +217,6 @@ DownwardMessages: StorageMap>; // (sender, receiver) // Sender posts, receiver drains HrmpChannels: StorageMap<(ParaId, ParaId), Deque>; - ``` --- @@ -511,7 +510,6 @@ pub struct OutboundHrmpMessage { /// The message payload. pub data: sp_std::vec::Vec, } - ``` --- diff --git a/content/polkadot/zombienet/slides.md b/content/polkadot/zombienet/slides.md index 2ca479c..81d7407 100644 --- a/content/polkadot/zombienet/slides.md +++ b/content/polkadot/zombienet/slides.md @@ -32,24 +32,33 @@ Zombienet is an integration testing tool that allow Integration tests are always complex: -
                +
                - Setup Configuration + + - Port management + + - Ready state off all artifacts + + - Observability + + - Leaking resources + ---v ## Friction to resolve -
                +
                - Config flexibility - Local environment @@ -62,7 +71,7 @@ Integration tests are always complex: ## Goals -
                +
                @@ -177,7 +186,7 @@ chmod +x zombienet ## But first, try manually… -
                +
                • Create chain-spec (parachain)
                @@ -188,7 +197,7 @@ parachain-template-node build-spec --chain local \
                -
                +
                • Create chain-spec (relay chain)
                @@ -208,30 +217,30 @@ Tutorials ### Add keys\* -
                +
                When not using --alice or --bob, you need to provide additional `aura` and `grandpa` keys and inject them into the keystore! (**per node**) ```sh - ./target/release/polkadot \ - key insert --base-path /tmp/node01 \ - --chain /tmp/relay.json \ - --scheme Sr25519 \ - --suri \ - --password-interactive \ - --key-type aura +./target/release/polkadot \ +key insert --base-path /tmp/node01 \ + --chain /tmp/relay.json \ + --scheme Sr25519 \ + --suri \ + --password-interactive \ + --key-type aura ``` -
                +
                ```sh - ./target/release/polkadot key insert \ - --base-path /tmp/node01 \ - --chain /tmp/relay.json \ - --scheme Ed25519 \ - --suri \ - --password-interactive \ - --key-type gran +./target/release/polkadot key insert \ + --base-path /tmp/node01 \ + --chain /tmp/relay.json \ + --scheme Ed25519 \ + --suri \ + --password-interactive \ + --key-type gran ``` Notes: @@ -298,7 +307,7 @@ parachain-template-node \ 1. Generate genesis wasm and state 1. Register parachain using sudo call -
                +
                ```sh[1,2|4,5|7,8] parachain-template-node build-spec --chain /tmp/para-raw.json \ @@ -395,7 +404,7 @@ Notes: Try to launch a network with `2` parachains. -
                +
                @@ -406,7 +415,7 @@ Try to launch a network with `2` parachains. The network definition supports using [nunjucks](https://mozilla.github.io/nunjucks/) templating language (similar to [tera](https://github.com/Keats/tera)). Where {{variables}} are replaced with env vars and you can use all the built-in features. -
                +
                ```toml[2] [relaychain] @@ -433,7 +442,7 @@ Zombienet providers allow to Kubernetes -
                +
                - Used internally, integrated with the [Grafana](https://grafana.com/oss/grafana/) stack. - You need to provide your infra stack. @@ -443,7 +452,7 @@ Zombienet providers allow to Podman -
                +
                - Automatically spawn and wire an instance of [Grafana](https://grafana.com/oss/grafana/) stack. - Attach a jaeger instance if enabled in the network definition. @@ -453,7 +462,7 @@ Zombienet providers allow to Native -
                +
                - Allow to attach to a running [Grafana](https://grafana.com/oss/grafana/) stack. **(wip)** @@ -478,7 +487,7 @@ Zombienet’s built-in test-runner allows users to ### Built-in assertions -
                +
                - Prometheus: Query the exposed metrics/histograms and assert on their values. diff --git a/content/security/infrastucutre/slides.md b/content/security/infrastucutre/slides.md index f4a73ab..2066203 100644 --- a/content/security/infrastucutre/slides.md +++ b/content/security/infrastucutre/slides.md @@ -348,7 +348,7 @@ It is the nature of git. A great field for social engineering! ### Exploiting git -Get a target repo, find a "victim" - a popular person,
                uses mixed verified and unverified commits: +Get a target repo, find a "victim" - a popular person,
                uses mixed verified and unverified commits: diff --git a/content/security/overview/slides.md b/content/security/overview/slides.md index 68a630a..8e71448 100644 --- a/content/security/overview/slides.md +++ b/content/security/overview/slides.md @@ -77,7 +77,7 @@ Notes: - - - -- +- - - - diff --git a/content/security/user-centric/slides.md b/content/security/user-centric/slides.md index 048a7f3..9bc510e 100644 --- a/content/security/user-centric/slides.md +++ b/content/security/user-centric/slides.md @@ -200,11 +200,11 @@ And the most important - and most of the time the weakest: how we handle these k -- Loss of confidentiality - your key is leaked or compromised.
                +- Loss of confidentiality - your key is leaked or compromised.
                i.e: someone else has access to the wallet. -- Loss of availability - you cannot access your key anymore.
                +- Loss of availability - you cannot access your key anymore.
                i.e: you don't know where you noted. -- Loss of integrity - your key is wrong.
                +- Loss of integrity - your key is wrong.
                i.e: you noted the key incorrectly.
                @@ -236,7 +236,7 @@ That they key is available - you can access to it when you need it - the hard di - One or more keys and a threshold -- The threshold defines how many signatories
                must sign for a sig check t be valid. +- The threshold defines how many signatories
                must sign for a sig check t be valid.
                @@ -457,7 +457,7 @@ He is the S on the RSA algorithm (Rivest-Shamir-Adleman) - Security is contextual - Define your risk appetite -- Backups not only of information also for processes.
                +- Backups not only of information also for processes.
                Do not rely on single point of failure. - Don't put all your eggs in the same basket @@ -510,9 +510,9 @@ He is the S on the RSA algorithm (Rivest-Shamir-Adleman) - Many actors or institutions have different objectives of the one you have. - Software have bugs and errors. - They are made by people like you and me,
                which needs to eat and go to sleep. + They are made by people like you and me,
                which needs to eat and go to sleep. - No technology is agnostic. - This includes they technology we communicate with,
                we work with or the one we use to keep us entertained. + This includes they technology we communicate with,
                we work with or the one we use to keep us entertained. - Sometimes we are our worst adversary. > Be diligent. 🖖 diff --git a/content/substrate/code/slides.md b/content/substrate/code/slides.md index 09b5f26..866ee91 100644 --- a/content/substrate/code/slides.md +++ b/content/substrate/code/slides.md @@ -152,7 +152,7 @@ Bute then each node can decide which subset of these it chooses, and how it impl Notes: - (seen env variables, pretty useful!) + (seen env variables, pretty useful!) ---v diff --git a/content/substrate/interact/slides.md b/content/substrate/interact/slides.md index 8052b71..d5bde21 100644 --- a/content/substrate/interact/slides.md +++ b/content/substrate/interact/slides.md @@ -39,7 +39,7 @@ almost all external communication happens over JSPN-RPC, so let's take a closer } ``` -
                +
                ```json { "jsonrpc": "2.0", "result": 19, "id": 3 } @@ -156,7 +156,7 @@ In Kusama: - The block number is stored under `twox128("System") ++ twox128("Number")`. - Find it now, and at block 10,000,000. -
                +
                - Refer to the "Substrate; Show Me The Code" lecture to find the right RPC endpoints. - You have 15 minutes! @@ -222,7 +222,6 @@ Please revise this while you learn FRAME, and they will make perfect sense! Notes: ```ts - import { ApiPromise, WsProvider } from "@polkadot/api"; const provider = new WsProvider("wss://rpc.polkadot.io"); const api = await ApiPromise.create({ provider }); diff --git a/content/substrate/intro/slides.md b/content/substrate/intro/slides.md index 009825d..18620e4 100644 --- a/content/substrate/intro/slides.md +++ b/content/substrate/intro/slides.md @@ -55,12 +55,19 @@ role in this scenario. ### Why Substrate? - ⛓️ Future is multi-chain. + + - 😭 Building a blockchain is hard. Upgrading it even harder. + + - 💡 Framework! + + - 🧐 But which attitude to take? + --- @@ -71,6 +78,7 @@ The **pre-substrate** way of thinking: - 😭 _Building a blockchain is hard. Upgrading it even harder_. - 💪🏻 We are going to spend maximal resources at making sure we get it right. + ---v @@ -80,10 +88,15 @@ The **pre-substrate** way of thinking: But has this worked? - 😭 Bitcoin block size debate + + - 2️⃣ L2s and beyond + + - 📈 Ethereum gas price + Notes: @@ -104,10 +117,15 @@ meet the demands of today. The **Substrate** way of thinking: - ☯️ Society and technology evolve + + - 🦸 Humans are fallible + + - 🧠 Best decision of today -> mistake of tomorrow + ---v @@ -154,7 +172,7 @@ int main() { } ``` -
                +
                ```rust fn main() { @@ -180,10 +198,9 @@ int main() { int* y = foo(); printf("%d\n", *y); // Accessing memory out of its scope } - ``` -
                +
                ```rust fn foo() -> &'static i32 { @@ -214,7 +231,7 @@ Notes: - 🏎️ Most Rust abstractions are **zero-cost**. - ⏰ Rust has (almost) no "runtime". -
                +
                @@ -242,14 +259,23 @@ needs of the future. ### 🤩 Generic, Modular and Extensible Design - Multiple consensus engines (BABE/Grandpa/AURA/PoW/Sassafras) + + - Multiple network protocols (QUIC, TCP) + + - Multiple database implementations (ParityDB, RocksDB) + + - Highly configurable, graph-based transaction-pool. + + - Easy to change primitives: AccountId, Signature, BlockNumber, Header, Hash, and many more. + Notes: @@ -288,10 +314,15 @@ particular implementation. - We have correct code, and components are easy to swap, replace, and upgrade. - What use is that, if we cannot agree on what to replace/upgrade? - Governance! + + - What use is governance, if the upgrade cannot be enacted? + + - (trustlessly) Upgradeability! + Notes: @@ -594,8 +625,11 @@ bug in it, everyone is affected. - Yes, consensus is not a core part of a blockchain runtime. Why? - Not part of your STF! + + - The consensus protocol is to your runtime what HTTP is to Facebook. + Notes: @@ -630,8 +664,11 @@ state is sometimes called "storage" asd well. - Yes, data is stored outside of the runtime. Why? - Wasm runtime does not have the means to store it. + + - Yet, the interpretation of the data is up to the runtime. + ---v @@ -985,12 +1022,9 @@ Notes: - - Substrate Primitives (`sp-*`), Frame (`frame-*`) and the pallets (`pallets-*`), binaries (`/bin`) - and all other utilities are licensed under [Apache - 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). + and all other utilities are licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). -Substrate Client (`/client/*` / `sc-*`) is licensed under [GPL -v3.0](https://www.gnu.org/licenses/gpl-3.0.html) with a [classpath linking -exception](https://www.gnu.org/software/classpath/license.html). +Substrate Client (`/client/*` / `sc-*`) is licensed under [GPL v3.0](https://www.gnu.org/licenses/gpl-3.0.html) with a [classpath linking exception](https://www.gnu.org/software/classpath/license.html). - Apache2 allows teams full freedom over what and how they release, and giving licensing clarity to commercial teams. diff --git a/content/substrate/scale/slides.md b/content/substrate/scale/slides.md index 248feed..4f8a6aa 100644 --- a/content/substrate/scale/slides.md +++ b/content/substrate/scale/slides.md @@ -171,7 +171,6 @@ fn main() { ```sh - 1000101 [45] [45] @@ -181,8 +180,6 @@ fn main() { 111111111111111111111111 [ff, ff, ff, 00] [00, ff, ff, ff] - - ``` diff --git a/content/substrate/storage/slides.md b/content/substrate/storage/slides.md index 946efff..46b2f43 100644 --- a/content/substrate/storage/slides.md +++ b/content/substrate/storage/slides.md @@ -241,7 +241,7 @@ Namely: - Substrate does in fact use a key-value based database under the hood.. - In order to store trie nodes, not direct storage keys! -
                +
                @@ -351,6 +351,7 @@ In general, you have a tradeoff: send more data, but require less hashing on Ali
                - Storage key is arbitrary length. +
                diff --git a/content/substrate/tips-tricks/slides.md b/content/substrate/tips-tricks/slides.md index 96fdb5f..c376fb0 100644 --- a/content/substrate/tips-tricks/slides.md +++ b/content/substrate/tips-tricks/slides.md @@ -461,7 +461,6 @@ impl Percent { impl Mul for Percent { ... } - ``` ---v @@ -518,7 +517,6 @@ let z = x * y; - [`big_uint.rs`](https://paritytech.github.io/substrate/master/sp_arithmetic/biguint/index.html) (unaudited) ```rust - pub struct BigUint { /// digits (limbs) of this number (sorted as msb -> lsb). pub(crate) digits: Vec, @@ -543,8 +541,8 @@ Things like **addition**, **multiplication**, **division** could all easily fail - Panic - `u32::MAX * 2 / 2` (in debug builds) - `100 / 0` - s -
                + +
                @@ -960,7 +958,7 @@ Notes: - First reminder: don't panic, unless if you want to punish someone! - `.unwrap()`? no no -
                +
                - be careful with implicit unwraps in standard operations! - slice/vector indexing can panic if out of bound diff --git a/content/substrate/wasm/slides.md b/content/substrate/wasm/slides.md index d6be25e..48a4ec1 100644 --- a/content/substrate/wasm/slides.md +++ b/content/substrate/wasm/slides.md @@ -24,7 +24,7 @@ duration: 60 minutes - Personal opinion: -> Substrate technology stack will put "Wasm stored onchain" on the map,
                +> Substrate technology stack will put "Wasm stored onchain" on the map,
                > the same way Ethereum put "smart contracts stored onchain" on the map. Notes: @@ -187,6 +187,7 @@ See Opaque. - Client's view of the transactions? 🤔 + Notes: @@ -341,8 +342,11 @@ Notes: - A state key is only meaningful at a given block. - A :code is only meaningful at at given block. + + - 💡 A runtime (API) is only meaningful when executed at a give block. + Notes: @@ -1216,6 +1220,7 @@ fn root(&mut self, version: StateVersion) -> Vec { .. } - Optional activity: Go to the substrate repo, and find PRs that have altered host functions, and see the PR discussion. There are a few labels that help you find such PRs 😉. + --- @@ -1227,57 +1232,57 @@ fn root(&mut self, version: StateVersion) -> Vec { .. } - `wasm2wat polkadot_runtime.wasm > dump | rg import` ``` - (import "env" "memory" (memory (;0;) 22)) - (import "env" "ext_crypto_ed25519_generate_version_1" (func $ext_crypto_ed25519_generate_version_1 (type 17))) - (import "env" "ext_crypto_ed25519_verify_version_1" (func $ext_crypto_ed25519_verify_version_1 (type 18))) - (import "env" "ext_crypto_finish_batch_verify_version_1" (func $ext_crypto_finish_batch_verify_version_1 (type 11))) - (import "env" "ext_crypto_secp256k1_ecdsa_recover_version_2" (func $ext_crypto_secp256k1_ecdsa_recover_version_2 (type 19))) - (import "env" "ext_crypto_secp256k1_ecdsa_recover_compressed_version_2" (func $ext_crypto_secp256k1_ecdsa_recover_compressed_version_2 (type 19))) - (import "env" "ext_crypto_sr25519_generate_version_1" (func $ext_crypto_sr25519_generate_version_1 (type 17))) - (import "env" "ext_crypto_sr25519_public_keys_version_1" (func $ext_crypto_sr25519_public_keys_version_1 (type 5))) - (import "env" "ext_crypto_sr25519_sign_version_1" (func $ext_crypto_sr25519_sign_version_1 (type 20))) - (import "env" "ext_crypto_sr25519_verify_version_2" (func $ext_crypto_sr25519_verify_version_2 (type 18))) - (import "env" "ext_crypto_start_batch_verify_version_1" (func $ext_crypto_start_batch_verify_version_1 (type 14))) - (import "env" "ext_misc_print_hex_version_1" (func $ext_misc_print_hex_version_1 (type 16))) - (import "env" "ext_misc_print_num_version_1" (func $ext_misc_print_num_version_1 (type 16))) - (import "env" "ext_misc_print_utf8_version_1" (func $ext_misc_print_utf8_version_1 (type 16))) - (import "env" "ext_misc_runtime_version_version_1" (func $ext_misc_runtime_version_version_1 (type 21))) - (import "env" "ext_hashing_blake2_128_version_1" (func $ext_hashing_blake2_128_version_1 (type 22))) - (import "env" "ext_hashing_blake2_256_version_1" (func $ext_hashing_blake2_256_version_1 (type 22))) - (import "env" "ext_hashing_keccak_256_version_1" (func $ext_hashing_keccak_256_version_1 (type 22))) - (import "env" "ext_hashing_twox_128_version_1" (func $ext_hashing_twox_128_version_1 (type 22))) - (import "env" "ext_hashing_twox_64_version_1" (func $ext_hashing_twox_64_version_1 (type 22))) - (import "env" "ext_storage_append_version_1" (func $ext_storage_append_version_1 (type 23))) - (import "env" "ext_storage_clear_version_1" (func $ext_storage_clear_version_1 (type 16))) - (import "env" "ext_storage_clear_prefix_version_2" (func $ext_storage_clear_prefix_version_2 (type 24))) - (import "env" "ext_storage_commit_transaction_version_1" (func $ext_storage_commit_transaction_version_1 (type 14))) - (import "env" "ext_storage_exists_version_1" (func $ext_storage_exists_version_1 (type 22))) - (import "env" "ext_storage_get_version_1" (func $ext_storage_get_version_1 (type 21))) - (import "env" "ext_storage_next_key_version_1" (func $ext_storage_next_key_version_1 (type 21))) - (import "env" "ext_storage_read_version_1" (func $ext_storage_read_version_1 (type 25))) - (import "env" "ext_storage_rollback_transaction_version_1" (func $ext_storage_rollback_transaction_version_1 (type 14))) - (import "env" "ext_storage_root_version_2" (func $ext_storage_root_version_2 (type 5))) - (import "env" "ext_storage_set_version_1" (func $ext_storage_set_version_1 (type 23))) - (import "env" "ext_storage_start_transaction_version_1" (func $ext_storage_start_transaction_version_1 (type 14))) - (import "env" "ext_trie_blake2_256_ordered_root_version_2" (func $ext_trie_blake2_256_ordered_root_version_2 (type 26))) - (import "env" "ext_offchain_is_validator_version_1" (func $ext_offchain_is_validator_version_1 (type 11))) - (import "env" "ext_offchain_local_storage_clear_version_1" (func $ext_offchain_local_storage_clear_version_1 (type 27))) - (import "env" "ext_offchain_local_storage_compare_and_set_version_1" (func $ext_offchain_local_storage_compare_and_set_version_1 (type 28))) - (import "env" "ext_offchain_local_storage_get_version_1" (func $ext_offchain_local_storage_get_version_1 (type 29))) - (import "env" "ext_offchain_local_storage_set_version_1" (func $ext_offchain_local_storage_set_version_1 (type 30))) - (import "env" "ext_offchain_network_state_version_1" (func $ext_offchain_network_state_version_1 (type 15))) - (import "env" "ext_offchain_random_seed_version_1" (func $ext_offchain_random_seed_version_1 (type 11))) - (import "env" "ext_offchain_submit_transaction_version_1" (func $ext_offchain_submit_transaction_version_1 (type 21))) - (import "env" "ext_offchain_timestamp_version_1" (func $ext_offchain_timestamp_version_1 (type 15))) - (import "env" "ext_allocator_free_version_1" (func $ext_allocator_free_version_1 (type 1))) - (import "env" "ext_allocator_malloc_version_1" (func $ext_allocator_malloc_version_1 (type 0))) - (import "env" "ext_offchain_index_set_version_1" (func $ext_offchain_index_set_version_1 (type 23))) - (import "env" "ext_default_child_storage_clear_version_1" (func $ext_default_child_storage_clear_version_1 (type 23))) - (import "env" "ext_default_child_storage_get_version_1" (func $ext_default_child_storage_get_version_1 (type 24))) - (import "env" "ext_default_child_storage_next_key_version_1" (func $ext_default_child_storage_next_key_version_1 (type 24))) - (import "env" "ext_default_child_storage_set_version_1" (func $ext_default_child_storage_set_version_1 (type 31))) - (import "env" "ext_logging_log_version_1" (func $ext_logging_log_version_1 (type 30))) - (import "env" "ext_logging_max_level_version_1" (func $ext_logging_max_level_version_1 (type 11))) +(import "env" "memory" (memory (;0;) 22)) +(import "env" "ext_crypto_ed25519_generate_version_1" (func $ext_crypto_ed25519_generate_version_1 (type 17))) +(import "env" "ext_crypto_ed25519_verify_version_1" (func $ext_crypto_ed25519_verify_version_1 (type 18))) +(import "env" "ext_crypto_finish_batch_verify_version_1" (func $ext_crypto_finish_batch_verify_version_1 (type 11))) +(import "env" "ext_crypto_secp256k1_ecdsa_recover_version_2" (func $ext_crypto_secp256k1_ecdsa_recover_version_2 (type 19))) +(import "env" "ext_crypto_secp256k1_ecdsa_recover_compressed_version_2" (func $ext_crypto_secp256k1_ecdsa_recover_compressed_version_2 (type 19))) +(import "env" "ext_crypto_sr25519_generate_version_1" (func $ext_crypto_sr25519_generate_version_1 (type 17))) +(import "env" "ext_crypto_sr25519_public_keys_version_1" (func $ext_crypto_sr25519_public_keys_version_1 (type 5))) +(import "env" "ext_crypto_sr25519_sign_version_1" (func $ext_crypto_sr25519_sign_version_1 (type 20))) +(import "env" "ext_crypto_sr25519_verify_version_2" (func $ext_crypto_sr25519_verify_version_2 (type 18))) +(import "env" "ext_crypto_start_batch_verify_version_1" (func $ext_crypto_start_batch_verify_version_1 (type 14))) +(import "env" "ext_misc_print_hex_version_1" (func $ext_misc_print_hex_version_1 (type 16))) +(import "env" "ext_misc_print_num_version_1" (func $ext_misc_print_num_version_1 (type 16))) +(import "env" "ext_misc_print_utf8_version_1" (func $ext_misc_print_utf8_version_1 (type 16))) +(import "env" "ext_misc_runtime_version_version_1" (func $ext_misc_runtime_version_version_1 (type 21))) +(import "env" "ext_hashing_blake2_128_version_1" (func $ext_hashing_blake2_128_version_1 (type 22))) +(import "env" "ext_hashing_blake2_256_version_1" (func $ext_hashing_blake2_256_version_1 (type 22))) +(import "env" "ext_hashing_keccak_256_version_1" (func $ext_hashing_keccak_256_version_1 (type 22))) +(import "env" "ext_hashing_twox_128_version_1" (func $ext_hashing_twox_128_version_1 (type 22))) +(import "env" "ext_hashing_twox_64_version_1" (func $ext_hashing_twox_64_version_1 (type 22))) +(import "env" "ext_storage_append_version_1" (func $ext_storage_append_version_1 (type 23))) +(import "env" "ext_storage_clear_version_1" (func $ext_storage_clear_version_1 (type 16))) +(import "env" "ext_storage_clear_prefix_version_2" (func $ext_storage_clear_prefix_version_2 (type 24))) +(import "env" "ext_storage_commit_transaction_version_1" (func $ext_storage_commit_transaction_version_1 (type 14))) +(import "env" "ext_storage_exists_version_1" (func $ext_storage_exists_version_1 (type 22))) +(import "env" "ext_storage_get_version_1" (func $ext_storage_get_version_1 (type 21))) +(import "env" "ext_storage_next_key_version_1" (func $ext_storage_next_key_version_1 (type 21))) +(import "env" "ext_storage_read_version_1" (func $ext_storage_read_version_1 (type 25))) +(import "env" "ext_storage_rollback_transaction_version_1" (func $ext_storage_rollback_transaction_version_1 (type 14))) +(import "env" "ext_storage_root_version_2" (func $ext_storage_root_version_2 (type 5))) +(import "env" "ext_storage_set_version_1" (func $ext_storage_set_version_1 (type 23))) +(import "env" "ext_storage_start_transaction_version_1" (func $ext_storage_start_transaction_version_1 (type 14))) +(import "env" "ext_trie_blake2_256_ordered_root_version_2" (func $ext_trie_blake2_256_ordered_root_version_2 (type 26))) +(import "env" "ext_offchain_is_validator_version_1" (func $ext_offchain_is_validator_version_1 (type 11))) +(import "env" "ext_offchain_local_storage_clear_version_1" (func $ext_offchain_local_storage_clear_version_1 (type 27))) +(import "env" "ext_offchain_local_storage_compare_and_set_version_1" (func $ext_offchain_local_storage_compare_and_set_version_1 (type 28))) +(import "env" "ext_offchain_local_storage_get_version_1" (func $ext_offchain_local_storage_get_version_1 (type 29))) +(import "env" "ext_offchain_local_storage_set_version_1" (func $ext_offchain_local_storage_set_version_1 (type 30))) +(import "env" "ext_offchain_network_state_version_1" (func $ext_offchain_network_state_version_1 (type 15))) +(import "env" "ext_offchain_random_seed_version_1" (func $ext_offchain_random_seed_version_1 (type 11))) +(import "env" "ext_offchain_submit_transaction_version_1" (func $ext_offchain_submit_transaction_version_1 (type 21))) +(import "env" "ext_offchain_timestamp_version_1" (func $ext_offchain_timestamp_version_1 (type 15))) +(import "env" "ext_allocator_free_version_1" (func $ext_allocator_free_version_1 (type 1))) +(import "env" "ext_allocator_malloc_version_1" (func $ext_allocator_malloc_version_1 (type 0))) +(import "env" "ext_offchain_index_set_version_1" (func $ext_offchain_index_set_version_1 (type 23))) +(import "env" "ext_default_child_storage_clear_version_1" (func $ext_default_child_storage_clear_version_1 (type 23))) +(import "env" "ext_default_child_storage_get_version_1" (func $ext_default_child_storage_get_version_1 (type 24))) +(import "env" "ext_default_child_storage_next_key_version_1" (func $ext_default_child_storage_next_key_version_1 (type 24))) +(import "env" "ext_default_child_storage_set_version_1" (func $ext_default_child_storage_set_version_1 (type 31))) +(import "env" "ext_logging_log_version_1" (func $ext_logging_log_version_1 (type 30))) +(import "env" "ext_logging_max_level_version_1" (func $ext_logging_max_level_version_1 (type 11))) ``` @@ -1287,74 +1292,74 @@ fn root(&mut self, version: StateVersion) -> Vec { .. } - `wasm2wat polkadot_runtime.wasm > dump | rg export` ``` - (export "__indirect_function_table" (table 0)) - (export "Core_version" (func $Core_version)) - (export "Core_execute_block" (func $Core_execute_block)) - (export "Core_initialize_block" (func $Core_initialize_block)) - (export "Metadata_metadata" (func $Metadata_metadata)) - (export "BlockBuilder_apply_extrinsic" (func $BlockBuilder_apply_extrinsic)) - (export "BlockBuilder_finalize_block" (func $BlockBuilder_finalize_block)) - (export "BlockBuilder_inherent_extrinsics" (func $BlockBuilder_inherent_extrinsics)) - (export "BlockBuilder_check_inherents" (func $BlockBuilder_check_inherents)) - (export "NominationPoolsApi_pending_rewards" (func $NominationPoolsApi_pending_rewards)) - (export "NominationPoolsApi_points_to_balance" (func $NominationPoolsApi_points_to_balance)) - (export "NominationPoolsApi_balance_to_points" (func $NominationPoolsApi_balance_to_points)) - (export "StakingApi_nominations_quota" (func $StakingApi_nominations_quota)) - (export "TaggedTransactionQueue_validate_transaction" (func $TaggedTransactionQueue_validate_transaction)) - (export "OffchainWorkerApi_offchain_worker" (func $OffchainWorkerApi_offchain_worker)) - (export "ParachainHost_validators" (func $ParachainHost_validators)) - (export "ParachainHost_validator_groups" (func $ParachainHost_validator_groups)) - (export "ParachainHost_availability_cores" (func $ParachainHost_availability_cores)) - (export "ParachainHost_persisted_validation_data" (func $ParachainHost_persisted_validation_data)) - (export "ParachainHost_assumed_validation_data" (func $ParachainHost_assumed_validation_data)) - (export "ParachainHost_check_validation_outputs" (func $ParachainHost_check_validation_outputs)) - (export "ParachainHost_session_index_for_child" (func $ParachainHost_session_index_for_child)) - (export "ParachainHost_validation_code" (func $ParachainHost_validation_code)) - (export "ParachainHost_candidate_pending_availability" (func $ParachainHost_candidate_pending_availability)) - (export "ParachainHost_candidate_events" (func $ParachainHost_candidate_events)) - (export "ParachainHost_session_info" (func $ParachainHost_session_info)) - (export "ParachainHost_dmq_contents" (func $ParachainHost_dmq_contents)) - (export "ParachainHost_inbound_hrmp_channels_contents" (func $ParachainHost_inbound_hrmp_channels_contents)) - (export "ParachainHost_validation_code_by_hash" (func $ParachainHost_validation_code_by_hash)) - (export "ParachainHost_on_chain_votes" (func $ParachainHost_on_chain_votes)) - (export "ParachainHost_submit_pvf_check_statement" (func $ParachainHost_submit_pvf_check_statement)) - (export "ParachainHost_pvfs_require_precheck" (func $ParachainHost_pvfs_require_precheck)) - (export "ParachainHost_validation_code_hash" (func $ParachainHost_validation_code_hash)) - (export "BeefyApi_beefy_genesis" (func $BeefyApi_beefy_genesis)) - (export "BeefyApi_validator_set" (func $BeefyApi_validator_set)) - (export "BeefyApi_submit_report_equivocation_unsigned_extrinsic" (func $BeefyApi_submit_report_equivocation_unsigned_extrinsic)) - (export "BeefyApi_generate_key_ownership_proof" (func $BeefyApi_generate_key_ownership_proof)) - (export "MmrApi_mmr_root" (func $MmrApi_mmr_root)) - (export "MmrApi_mmr_leaf_count" (func $MmrApi_mmr_leaf_count)) - (export "MmrApi_generate_proof" (func $MmrApi_generate_proof)) - (export "MmrApi_verify_proof" (func $MmrApi_verify_proof)) - (export "MmrApi_verify_proof_stateless" (func $MmrApi_verify_proof_stateless)) - (export "GrandpaApi_grandpa_authorities" (func $GrandpaApi_grandpa_authorities)) - (export "GrandpaApi_current_set_id" (func $GrandpaApi_current_set_id)) - (export "GrandpaApi_submit_report_equivocation_unsigned_extrinsic" (func $GrandpaApi_submit_report_equivocation_unsigned_extrinsic)) - (export "GrandpaApi_generate_key_ownership_proof" (func $GrandpaApi_generate_key_ownership_proof)) - (export "BabeApi_configuration" (func $BabeApi_configuration)) - (export "BabeApi_current_epoch_start" (func $BabeApi_current_epoch_start)) - (export "BabeApi_current_epoch" (func $BabeApi_current_epoch)) - (export "BabeApi_next_epoch" (func $BabeApi_next_epoch)) - (export "BabeApi_generate_key_ownership_proof" (func $BabeApi_generate_key_ownership_proof)) - (export "BabeApi_submit_report_equivocation_unsigned_extrinsic" (func $BabeApi_submit_report_equivocation_unsigned_extrinsic)) - (export "AuthorityDiscoveryApi_authorities" (func $AuthorityDiscoveryApi_authorities)) - (export "SessionKeys_generate_session_keys" (func $SessionKeys_generate_session_keys)) - (export "SessionKeys_decode_session_keys" (func $SessionKeys_decode_session_keys)) - (export "AccountNonceApi_account_nonce" (func $AccountNonceApi_account_nonce)) - (export "TransactionPaymentApi_query_info" (func $TransactionPaymentApi_query_info)) - (export "TransactionPaymentApi_query_fee_details" (func $TransactionPaymentApi_query_fee_details)) - (export "TransactionPaymentApi_query_weight_to_fee" (func $TransactionPaymentApi_query_weight_to_fee)) - (export "TransactionPaymentApi_query_length_to_fee" (func $TransactionPaymentApi_query_length_to_fee)) - (export "TransactionPaymentCallApi_query_call_info" (func $TransactionPaymentCallApi_query_call_info)) - (export "TransactionPaymentCallApi_query_call_fee_details" (func $TransactionPaymentCallApi_query_call_fee_details)) - (export "TransactionPaymentCallApi_query_weight_to_fee" (func $TransactionPaymentCallApi_query_weight_to_fee)) - (export "TransactionPaymentCallApi_query_length_to_fee" (func $TransactionPaymentCallApi_query_length_to_fee)) - (export "TryRuntime_on_runtime_upgrade" (func $TryRuntime_on_runtime_upgrade)) - (export "TryRuntime_execute_block" (func $TryRuntime_execute_block)) - (export "__data_end" (global 1)) - (export "__heap_base" (global 2)) +(export "__indirect_function_table" (table 0)) +(export "Core_version" (func $Core_version)) +(export "Core_execute_block" (func $Core_execute_block)) +(export "Core_initialize_block" (func $Core_initialize_block)) +(export "Metadata_metadata" (func $Metadata_metadata)) +(export "BlockBuilder_apply_extrinsic" (func $BlockBuilder_apply_extrinsic)) +(export "BlockBuilder_finalize_block" (func $BlockBuilder_finalize_block)) +(export "BlockBuilder_inherent_extrinsics" (func $BlockBuilder_inherent_extrinsics)) +(export "BlockBuilder_check_inherents" (func $BlockBuilder_check_inherents)) +(export "NominationPoolsApi_pending_rewards" (func $NominationPoolsApi_pending_rewards)) +(export "NominationPoolsApi_points_to_balance" (func $NominationPoolsApi_points_to_balance)) +(export "NominationPoolsApi_balance_to_points" (func $NominationPoolsApi_balance_to_points)) +(export "StakingApi_nominations_quota" (func $StakingApi_nominations_quota)) +(export "TaggedTransactionQueue_validate_transaction" (func $TaggedTransactionQueue_validate_transaction)) +(export "OffchainWorkerApi_offchain_worker" (func $OffchainWorkerApi_offchain_worker)) +(export "ParachainHost_validators" (func $ParachainHost_validators)) +(export "ParachainHost_validator_groups" (func $ParachainHost_validator_groups)) +(export "ParachainHost_availability_cores" (func $ParachainHost_availability_cores)) +(export "ParachainHost_persisted_validation_data" (func $ParachainHost_persisted_validation_data)) +(export "ParachainHost_assumed_validation_data" (func $ParachainHost_assumed_validation_data)) +(export "ParachainHost_check_validation_outputs" (func $ParachainHost_check_validation_outputs)) +(export "ParachainHost_session_index_for_child" (func $ParachainHost_session_index_for_child)) +(export "ParachainHost_validation_code" (func $ParachainHost_validation_code)) +(export "ParachainHost_candidate_pending_availability" (func $ParachainHost_candidate_pending_availability)) +(export "ParachainHost_candidate_events" (func $ParachainHost_candidate_events)) +(export "ParachainHost_session_info" (func $ParachainHost_session_info)) +(export "ParachainHost_dmq_contents" (func $ParachainHost_dmq_contents)) +(export "ParachainHost_inbound_hrmp_channels_contents" (func $ParachainHost_inbound_hrmp_channels_contents)) +(export "ParachainHost_validation_code_by_hash" (func $ParachainHost_validation_code_by_hash)) +(export "ParachainHost_on_chain_votes" (func $ParachainHost_on_chain_votes)) +(export "ParachainHost_submit_pvf_check_statement" (func $ParachainHost_submit_pvf_check_statement)) +(export "ParachainHost_pvfs_require_precheck" (func $ParachainHost_pvfs_require_precheck)) +(export "ParachainHost_validation_code_hash" (func $ParachainHost_validation_code_hash)) +(export "BeefyApi_beefy_genesis" (func $BeefyApi_beefy_genesis)) +(export "BeefyApi_validator_set" (func $BeefyApi_validator_set)) +(export "BeefyApi_submit_report_equivocation_unsigned_extrinsic" (func $BeefyApi_submit_report_equivocation_unsigned_extrinsic)) +(export "BeefyApi_generate_key_ownership_proof" (func $BeefyApi_generate_key_ownership_proof)) +(export "MmrApi_mmr_root" (func $MmrApi_mmr_root)) +(export "MmrApi_mmr_leaf_count" (func $MmrApi_mmr_leaf_count)) +(export "MmrApi_generate_proof" (func $MmrApi_generate_proof)) +(export "MmrApi_verify_proof" (func $MmrApi_verify_proof)) +(export "MmrApi_verify_proof_stateless" (func $MmrApi_verify_proof_stateless)) +(export "GrandpaApi_grandpa_authorities" (func $GrandpaApi_grandpa_authorities)) +(export "GrandpaApi_current_set_id" (func $GrandpaApi_current_set_id)) +(export "GrandpaApi_submit_report_equivocation_unsigned_extrinsic" (func $GrandpaApi_submit_report_equivocation_unsigned_extrinsic)) +(export "GrandpaApi_generate_key_ownership_proof" (func $GrandpaApi_generate_key_ownership_proof)) +(export "BabeApi_configuration" (func $BabeApi_configuration)) +(export "BabeApi_current_epoch_start" (func $BabeApi_current_epoch_start)) +(export "BabeApi_current_epoch" (func $BabeApi_current_epoch)) +(export "BabeApi_next_epoch" (func $BabeApi_next_epoch)) +(export "BabeApi_generate_key_ownership_proof" (func $BabeApi_generate_key_ownership_proof)) +(export "BabeApi_submit_report_equivocation_unsigned_extrinsic" (func $BabeApi_submit_report_equivocation_unsigned_extrinsic)) +(export "AuthorityDiscoveryApi_authorities" (func $AuthorityDiscoveryApi_authorities)) +(export "SessionKeys_generate_session_keys" (func $SessionKeys_generate_session_keys)) +(export "SessionKeys_decode_session_keys" (func $SessionKeys_decode_session_keys)) +(export "AccountNonceApi_account_nonce" (func $AccountNonceApi_account_nonce)) +(export "TransactionPaymentApi_query_info" (func $TransactionPaymentApi_query_info)) +(export "TransactionPaymentApi_query_fee_details" (func $TransactionPaymentApi_query_fee_details)) +(export "TransactionPaymentApi_query_weight_to_fee" (func $TransactionPaymentApi_query_weight_to_fee)) +(export "TransactionPaymentApi_query_length_to_fee" (func $TransactionPaymentApi_query_length_to_fee)) +(export "TransactionPaymentCallApi_query_call_info" (func $TransactionPaymentCallApi_query_call_info)) +(export "TransactionPaymentCallApi_query_call_fee_details" (func $TransactionPaymentCallApi_query_call_fee_details)) +(export "TransactionPaymentCallApi_query_weight_to_fee" (func $TransactionPaymentCallApi_query_weight_to_fee)) +(export "TransactionPaymentCallApi_query_length_to_fee" (func $TransactionPaymentCallApi_query_length_to_fee)) +(export "TryRuntime_on_runtime_upgrade" (func $TryRuntime_on_runtime_upgrade)) +(export "TryRuntime_execute_block" (func $TryRuntime_execute_block)) +(export "__data_end" (global 1)) +(export "__heap_base" (global 2)) ``` ---v diff --git a/content/xcm/beyond/slides.md b/content/xcm/beyond/slides.md index 0182c40..9907bb5 100644 --- a/content/xcm/beyond/slides.md +++ b/content/xcm/beyond/slides.md @@ -197,7 +197,6 @@ MultiLocation { Junction::GeneralIndex(0u128), ), } - ``` ---v @@ -327,7 +326,6 @@ stateDiagram-v2 ### Matching NFTs ```rust [0|4-15|18-21] - MultiAsset { // Where to find the NFT (contract or collection in an NFT pallet) id: AssetId::Concrete ( @@ -350,7 +348,6 @@ MultiAsset { AssetInstance::Instance(nft_id) ) } - ``` ---v @@ -518,6 +515,8 @@ During this presentation we went through a couple real world XCM use cases and s ## References - [XCM source code](https://github.com/paritytech-stg/polkadot-sdk/tree/master/polkadot/xcm) - The source code for the main XCM implementation in the paritytech/polkadot repository. + + - [XCM Documentation](https://paritytech.github.io/xcm-docs) - The official documentation for XCM: Cross-Consensus Messaging. - [InvArch's Pallet Rings](https://github.com/InvArch/InvArch-Frames/tree/main/pallet-rings) - Reference implementation of an XCM abstraction pallet for XCMultisigs. diff --git a/content/xcm/config/slides.md b/content/xcm/config/slides.md index 5191bcb..24bb44e 100644 --- a/content/xcm/config/slides.md +++ b/content/xcm/config/slides.md @@ -138,7 +138,6 @@ Notes: - `HashedDescription`: Hashes the description of a `Location` and converts that into an `AccountId`. ```rust - pub struct HashedDescription(PhantomData<(AccountId, Describe)>); impl< AccountId: From<[u8; 32]> + Clone, diff --git a/content/xcm/in-use/slides.md b/content/xcm/in-use/slides.md index 79c4627..398398f 100644 --- a/content/xcm/in-use/slides.md +++ b/content/xcm/in-use/slides.md @@ -81,7 +81,7 @@ To execute this operation, we will interact with the following components: - Source XCM Version: V3 - Source Extrinsic: `xcmTransactor.transactThroughSigned` -
                Consequently, it will initiate the remote execution of the following call: +
                Consequently, it will initiate the remote execution of the following call: - Target Chain: Turing Network - Target XCM Version: V3 @@ -117,7 +117,7 @@ Moonriver has further encapsulated the function to make their own xcmTransactor. ---v -1. Ensure Barriers on the recipient chain.
                +1. Ensure Barriers on the recipient chain.
                In this case, an Allow Barrier\*\* `WithComputedOrigin`, needs to be configured in the XCM config of Turing Network. This Barrier will allow the DescendOrigin instruction in XCM, which will reassign the origination of the transaction on Turing from Moonriver's sovereign account to the user's proxy account. 1. Configure user’s remote wallet on the recipient chainThe remote wallet, or proxy wallet acts as an account abstraction, allowing the blockchain to execute specific code on behalf of the user. @@ -144,7 +144,7 @@ This extrinsic serves as the gateway to composing the XCM message, incorporating ## XCM configs -The following are the parameters you need to decide before sending an XCM message:

                +The following are the parameters you need to decide before sending an XCM message:

                1. **Version number**: Check the XCM version on both recipient (Turing Network) and source (Moonriver) chains. Ensure their XCM versions are compatible. @@ -174,7 +174,7 @@ It requires the following parameters: **Destination**: It specifies the target chain, or for our case, the Turing Network, identified by {Relay, 2114} on Kusama. -
                +
                diff --git a/content/xcm/pallet/slides.md b/content/xcm/pallet/slides.md index a7b051e..651434d 100644 --- a/content/xcm/pallet/slides.md +++ b/content/xcm/pallet/slides.md @@ -84,14 +84,12 @@ Notes: Executed on behalf of FRAME's signed origin. - flowchart TD subgraph paraA[Parachain A              .] executor --"success?"--> palletxcm palletxcm("pallet-xcm") --"execute"--> executor("xcm-executor") end execute("execute(xcm)") --> palletxcm - Notes: @@ -108,21 +106,16 @@ It executes the message **locally** and returns the outcome as an event. Sends a message to the provided destination. - flowchart LR subgraph paraA[Parachain A] -palletxcma("pallet-xcm") --"deliver"--> routera("xcm-router") -routera --> mqueuea("message queue") + palletxcma("pallet-xcm") --"deliver"--> routera("xcm-router") + routera --> mqueuea("message queue") end - subgraph paraB[Parachain B] mqueueb("message queue") --> executorb("xcm-executor") end - send("send(xcm)") --> palletxcma mqueuea --> mqueueb - - Notes: @@ -158,22 +151,16 @@ We have already seen what teleports and reserve transfers mean in lesson 7.1; A This extrinsic allows the user to perform an asset teleport. - flowchart LR subgraph paraA[Parachain A] palletxcma("pallet-xcm") --"1. execute"--> executora("xcm-executor") executora --"send"--> sendera("xcm-sender") end - subgraph tdestination[Trusted Destination] end lteleport("limited_teleport_assets(\n  dest,\n  beneficiary,\n  assets,\n  fee_asset_item,\n  weight_limit\n)"):::left --> palletxcma - sendera --"2."--> tdestination - classDef left text-align:left - - ---v @@ -214,22 +201,16 @@ Xcm(vec![ Allow the user to perform a reserve-backed transfer from the reserve chain to the destination. - flowchart LR subgraph reserve[Reserve Chain] palletxcma("pallet-xcm") --"1. execute"--> executora("xcm-executor") executora --"send"--> sendera("xcm-sender") end - subgraph destination[Destination] end lteleport("limited_reserve_transfer_assets(\n  dest,\n  beneficiary,\n  assets,\n  fee_asset_item,\n  weight_limit\n)"):::left --> palletxcma - sendera --"2."--> destination - classDef left text-align:left - - ---v @@ -323,11 +304,11 @@ Notes: ```rust - impl Config for XcmConfig { - // --snip-- - type ResponseHandler = PalletXcm; - type SubscriptionService = PalletXcm; - } +impl Config for XcmConfig { + // --snip-- + type ResponseHandler = PalletXcm; + type SubscriptionService = PalletXcm; +} ``` Notes: @@ -383,7 +364,6 @@ XCM version negotiation: In the following scenario Chain A is using XCM v2 - flowchart BT subgraph registryA[Chain A's Registry] chainB("Chain B \n\n v2") @@ -391,16 +371,11 @@ subgraph registryA[Chain A's Registry] chainD("Chain D \n\n v1") chainE("Chain E \n\n v3") end - - flowchart LR - chainARequest("Chain A") --"Chain E ? \n\n v2"--> chainERequest("Chain E") - - --- diff --git a/reveal.json b/reveal.json index 4ef9f30..102023f 100644 --- a/reveal.json +++ b/reveal.json @@ -1,13 +1,13 @@ { - "width": 1400, - "height": 900, - "margin": 0, - "minScale": 0.2, - "maxScale": 2.0, - "transition": "none", - "controls": true, - "progress": true, - "center": true, - "slideNumber": true, - "backgroundTransition": "fade" + "width": 1400, + "height": 900, + "margin": 0, + "minScale": 0.2, + "maxScale": 2.0, + "transition": "none", + "controls": true, + "progress": true, + "center": true, + "slideNumber": true, + "backgroundTransition": "fade" } diff --git a/tools/plugin/mermaid-theme.js b/tools/plugin/mermaid-theme.js index f861548..0513f2f 100644 --- a/tools/plugin/mermaid-theme.js +++ b/tools/plugin/mermaid-theme.js @@ -1,35 +1,34 @@ - // Mermaid theme and functions - const pink = '#E6007A'; - const purple = '#442299'; - const lightPurple = '#6D3AEE'; - const white = '#FFFFFF'; +// Mermaid theme and functions +const pink = "#E6007A"; +const purple = "#442299"; +const lightPurple = "#6D3AEE"; +const white = "#FFFFFF"; - Reveal.addEventListener('ready', event => asyncMermaidRender(event)); +Reveal.addEventListener("ready", event => asyncMermaidRender(event)); - async function asyncMermaidRender(event) { - var graphs = document.querySelectorAll(".mermaid"); - graphs.forEach((item, index) => { - let graphCode = item.textContent.trim(); //trim() becase of gantt, class and git diagram - let mermaidDiv = document.createElement('div'); - mermaidDiv.classList.add('mermaid'); - mermaidDiv.setAttribute("data-processed", "true"); +async function asyncMermaidRender(event) { + var graphs = document.querySelectorAll(".mermaid"); + graphs.forEach((item, index) => { + let graphCode = item.textContent.trim(); // trim() becase of gantt, class and git diagram + let mermaidDiv = document.createElement("div"); + mermaidDiv.classList.add("mermaid"); + mermaidDiv.setAttribute("data-processed", "true"); - try { - // item.innerText ignores html elements added by revealjs highlight plugin. - mermaid.mermaidAPI.render('theGraph' + index, graphCode, function(svgCode) { - mermaidDiv.innerHTML = svgCode; - }); + try { + // item.innerText ignores html elements added by revealjs highlight plugin. + mermaid.mermaidAPI.render("theGraph" + index, graphCode, function(svgCode) { + mermaidDiv.innerHTML = svgCode; + }); - let parentDiv = document.createElement('div'); - parentDiv.appendChild(mermaidDiv); - parentDiv.style.width = '100%'; - parentDiv.style.height = '100%'; - item.parentNode.parentNode.insertBefore(parentDiv, item.parentNode); - item.parentNode.remove(); - } - catch(err) { - console.log("Cannot render mermaid diagram " + index + "\n" + graphCode); - console.log(err.message); - } - }) - } + let parentDiv = document.createElement("div"); + parentDiv.appendChild(mermaidDiv); + parentDiv.style.width = "100%"; + parentDiv.style.height = "100%"; + item.parentNode.parentNode.insertBefore(parentDiv, item.parentNode); + item.parentNode.remove(); + } catch (err) { + console.log("Cannot render mermaid diagram " + index + "\n" + graphCode); + console.log(err.message); + } + }); +}
                Database