bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 18쪽 중 14쪽
s: a malicious prover can redirect the chain to a sibling MSU that genuinely does not contain the key, present an honest non-existence path inside that wrong MSU, and the sibling-leftmost-leaf subchains will still close to the unchanged `root_hash`. The 16-slot pinning argument constrains internal layers within an MSU but does not by itself constrain which MSU subtree was descended into. The key→MSU-slot derivation is therefore load-bearing and must be enforced before any other check.
Letus skips committed empty slots when computing hashes for internal nodes (see the loop illustration earlier), therefore:
* The same root\_hash may correspond to multiple "logical tree shapes" (which slots are empty, how nodes are laid out), and the proof\_node byte layout seen by the verifier from the SPV may not necessarily correspond one-to-one with the "complete 16-ary expanded diagram".
* However, this does not weaken the SPV's goal: The verifier only cares about "whether the path of this key is consistent with the root commitment under the current hash rules". Skipping empty slots changes "how to compress and encode child hashes", but does not change the commitment relationship that "non-empty subtree hashes are rolled into the root by the parent node and ancestors all the way".
Under this premise, when the hash function satisfies the expected cryptographic properties (collision resistance, preimage resistance; corresponding to the algorithms used in ComputeKeyHash, node hashes, etc. in the implementation), it can be considered that:
* An attacker cannot tamper with a valid existence proof for a certain key and turn it into a valid non-existence proof for the same key;
* Nor can they tamper with a valid non-existence proof and turn it into a valid existence proof for the same key.
(If hashes could be arbitrarily collided or preimages could be found, the above conclusions would no longer hold; the arguments below all assume "ideal" hash behavior.)
### Existence Proof Case Discussion
An existence proof must simultaneously satisfy: rolling hashes from bottom to top are consistent with root\_hash, and the key\_hash in the leaf is consistent with the hash computed from the queried key using the same rules.
The key points of reliability can be broken down into three layers:
1. **Leaf Layer Binding** The leaf node encoding contains key\_hash (and value-side commitments). The verifier explicitly checks that the key\_hash in the leaf is consistent with `ComputeKeyHash(query key)`, which is equivalent to requiring that "this existence claim is bound to this key", not some other preimage.
2. **Path and Slot Consistency** In each layer's internal node, the 32-byte subtree root hash of the child slot must be consistent with the "current subtree root" being verified; and the slot\_idx used by the verifier to select slots is derived entirely from the nibble path of the **same key\_hash**. Therefore, an attacker cannot disguise a "subtree hash pointing elsewhere" as "the one that should be seen when going down along the query key", unless they can break the binding between the parent node hash and the child slot content (which boils down to hash collision or forging node encoding).
3. **Root Anchoring** The final `tmp_hash == root_hash` pins the entire path to that version of the state. If the root comes from a trusted source, then the meaning of "exists (K, V)" under that version is fixed jointly by the tree and encoding rules.
**In summary**: The three-layer checks of leaf—path—root together ensure that the "claimed existing key" aligns with the "actual leaf content on the Merkle path" and the "global state commitment".
### Non-Existence Proof Case Discussion - Case 1
**Case 1**: Following the nibble path of the query key leads to a leaf, but the key\_hash in the leaf ≠ `ComputeKeyHash(query key)` (reaching "someone else's leaf" — the path prefix overlaps with another, and the last hop lands on an already existing different key).
**Argument**:
1. **Path Authenticity** If the proof chain can close from bottom to top to root\_hash under the slot\_idx (and next\_begin\_offset consistency) at each layer derived from the query key, it indicates: On the slot sequence that the key claims to follow, the Merkle structure is self-consistent, not randomly assembled isolated nodes.
2. **Uniqueness Semantics of Leaf Content** The key\_hash in the leaf is obtained from the key at storage time using the same hash rules. In the sense of preimage resistance, it is impossible to forge a value for the "query key" that is the same as the key\_hash already written in the leaf, unless by chance of collision or it is the original key. What is written in the leaf is the hash of "another key", so the query key is not the key bound by that leaf.
3. **Conclusion** Chain verification passes ⇒ There is indeed a leaf hanging at the end of the query path on the tree; the key bound in the leaf is determined and is not the query key ⇒ In that version of the state, one cannot claim that the query key exists using that leaf as evidence. This is the semantics of "non-existence" in Case 1.
### Non-Existence Proof Case Discussion - Case 2
**Case 2**: At a certain internal node in the query path, the next nibble corresponds to an empty slot, the main chain tree\_proofs ends at the internal node without passing through a leaf.
#### Why "Only Main Chain, No Sibling Information" Is Not Sufficient
When only providing node material for "walking to a certain layer's internal node along the query key, with the next slot being empty", the verifier can only confirm: On the chain provided by the attacker, the sub-slot in the query direction appears to be empty. However, the SkipEmpty and sparse Trie encoding methods make the "appearance of the intermediate" less transparent in the proof than the "entire subtree commitment": A malicious Prover could theoretically attempt to construct a kind of local view — pretending the slot is empty on the query nibble, while concealing or forging the subtrees that actually exist on other slots at the same layer, as long as those slots' real paths and leaf bindings below have not been required to be shown.
In other words: Relying solely on the main chain of "empty slot termination" is not sufficient to prove that "the subtree hashes on other non-empty slots at the same layer are also consistent with the current parent node, ancestors, and root"; without constraints on the "side branches", the "emptiness" could be fabricated.
```plaintext
Suppose a malicious full node wants to forge a proof of "key K does not exist" to a light client, but K actually exists in the Trie:
1. Layout of the Real Internal Node (depth=d):
slot[2] = H_child_a
slot[7] = H_child_k - Key K's path key_hash[d]=7 leads here (non-empty, indicating K exists)
slot[11] = H_child_c
All other slots are empty (all zeros)
2. Forged Internal Node Constructed by the Attacker:
slot[2] = H_child_a
slot[7] = all zeros // "Vacate" this slot
slot[9] = H_child_k // Move H_child_k to another empty slot
slot[11] = H_child_c
All other slots are empty (all zeros)
3. The Hashes of Both Nodes Are Identical, Because:
Real: SHA256(type || padding || H_child_a || H_child_k || H_child_c)
Forged: SHA256(type || padding || H_child_a || H_child_k || H_child_c)
The concatenation order of non-empty hashes remains unchanged (it's the order encountered when scanning slots 0-15); only the positions have changed.
4. Verifier checks slot[7] and finds all zeros, concluding K does not exist
5. Verifier executes HashInternalNodeSkipEmpty and obtains the same hash as the real node
6. Tracing up the path to the root, the child hash recorded in the parent node matches
7. Result: The light client is deceived - it believes K does not exist, but K actually exists!
```
The figure above illustrates this kind of tampering/concealment: For example, the attacker lets the query path stop at an empty slot in the narrative, but does not synchronously provide sibling branch information consistent with the real state.
#### What Role Do sibling\_leftmost\_leaf\_proofs Play
For each non-empty sibling slot that needs to be declared as "indeed having data at the same layer", the Prover additionally provides `sibling_leftmost_leaf_proofs`: for the key of the leftmost leaf in that slot's subtree, and a sub-chain from a certain layer's internal node (sharing a prefix with the main chain) down to that leaf along the "leftmost path" (see the combined in the instance pseudocode earlier).
During verification:
1. The main chain still verifies according to the query key's slot\_idx to the internal node where "empty slot termination" occurs, and closes with root\_hash.
2. Each sibling sub-proof, after concatenating "the main chain minus the last section" with proof\_path, rolls to the **same** root\_hash in the manner of an existence proof, recalculating the slot indices at each layer using leftmost\_leaf\_key.
In this way, under the same parent node (and ancestors), the "empty slot" in the query direction and the "non-empty subtree down to a certain leaf" in the sibling direction are simultaneously constrained by the same root commitment: The subtree hashes of each non-empty slot in the parent internal must be able to support both the empty slot narrative on the main chain and the sibling chains going all the way down to real leaf nodes; both must be consistent with the parent hash computed under the node encoding and SkipEmpty rules.
#### Why It Is Difficult for an Attacker to Forge Sibling Chains
The verification of sibling chains uses the **own nibble path of leftmost\_leaf\_key**, not the path of the query key. Therefore:
* One cannot arbitrarily take "any other leaf on the tree" to impersonate the "leftmost leaf" of that slot, unless going down from the leftmost path along leftmost\_leaf\_key, the next\_begin\_offset / slot\_idx at each layer are consistent with the encoding and close to the root — this is equivalent to performing a complete existence-style verification for that key.
* One cannot simply reuse "another key" as leftmost\_leaf\_key without regard to the path: If that key is not the leftmost leaf in that slot's subtree, or if its slot positions at deeper layers are inconsistent with the structure implied by proof\_path, the verification will fail at some layer.
* Under the assumptions of preimage resistance and collision resistance, forging a sibling chain that can pass verification means forging node content and leaf bindings compatible with the real root\_hash, which is computationally infeasible.
**Summary (Correctness Discussion)**: Existence relies on leaf key binding + path slots + root; Case 1 relies on path authenticity + leaf bound to non-query key; Case 2 uses sibling leftmost leaf existence sub-chains in addition to the empty slot main chain to pin non-empty branches at the same layer to the same root\_hash, thereby plugging the gap of "only fabricating a segment of internal". All three are compatible with Letus's SkipEmpty encoding: not pursuing "one-to-one correspondence between proof and unique tree shape", but pursuing "semantic consistency under root commitment, and types cannot be mutually tampered".
# Foundry
This guide is suitable for developers who want to start building dApps using Pharos and Foundry toolchains. If you are a new user of Ethereum, please consider researching the [Ethereum documentation](https://ethereum.org/en/developers/docs/) before continuing.
## Write Your First Transaction
This guide will walk you through the process of sending your first transaction on the Pharos blockchain using three popular libraries: `ethers.js`, `web3.js`, and `web3.py`. By the end of this guide, you will understand how to send a transaction programmatically using these libraries.
### Prerequisites
Before you begin, ensure you have the following:
* Git: Used for code management and obtain examples.
* Pharos Devnet/Testnet Access: Access to a Pharos node (local or remote) for interacting with the blockchain.
### Setup 1: Pick Your Favorite Contract Develop Framework and IDE
Install your preferred contract framework from the below list:
* ethers.js
* web3.js
* web3.py
### Setup 2: Set Up the Project
Clone the example repo and add dependencies.
```sh
git clone https://github.com/PharosNetwork/examples
cd examples/transaction/ethersjs
npm install
```
```javascript
const { ethers } = require("ethers");
// Connect to Pharos Testnet
const provider = new ethers.providers.JsonRpcProvider("<PHAROS_RPC_URL>");
// Note: Your wallet private key (for testnet only, never expose this in production)
const privateKey = "YOUR_PRIVATE_KEY";
const wallet = new ethers.Wallet(privateKey, provider);
// Transaction details
const tx = {
to: "RECIPIENT_ADDRESS", // Note: Replace with the recipient's address
value: ethers.utils.parseEther("0.1"), // Amount to send (0.1 PHAR)
};
// Send the transaction
wallet.sendTransaction(tx)
.then((transaction) => {
console.log("Transaction sent:", transaction.hash);
})
.catch((error) => {
console.error("Error sending transaction:", error);
});
```
### Step 3: Run the Script
Run the script using Node.js:
<pre class="language-sh"><code class="lang-sh"><strong>node index.js
</strong></code></pre>
### Key Points
* **Private Key**: Never expose your private key in production. Use environment variables or secure storage.
* **Recipient Address**: Replace RECIPIENT\_ADDRESS with the actual recipient's wallet address.
* **Gas Limit**: Ensure you include a sufficient gas limit for the transaction.
### Troubleshooting
* **Transaction Fails**: Ensure you have enough testnet tokens to cover the transaction fee.
* **Incorrect Network**: Double-check that you are connected to the Pharos Testnet.
* **Invalid Address**: Verify that the recipient's address is correct.
### Conclusion
Now that you’ve sent your first transaction using ethers.js, web3.js, and web3.py.
This guide provides a comprehensive introduction to sending transactions on the Pharos blockchain using three popular libraries. If you encounter any issues, refer to the Troubleshooting section or consult the respective library's documentation. Happy building! 🚀
# Write Your First dApp
This guide will walk you through the process of building and deploying your first end-to-end decentralized application (dApp) on the Pharos blockchain. By the end of this guide, you will have a fully functional dApp that includes a smart contract, a backend, and a frontend.
### Prerequisites
Before you begin, ensure you have the following:
* Git: Used for code management and obtain examples.
* Node.js: Install it from [nodejs.org](https://nodejs.org/).
* Pharos Devnet/Testnet Access: Access to a Pharos node (local or remote) for interacting with the blockchain.
### Setup 1: Install Foundry
* [Foundry](https://book.getfoundry.sh/getting-started/installation)
### Setup 2: Set Up the Project
Clone the example repo:
```sh
git clone https://github.com/PharosNetwork/examples
cd examples/dapp/foundry
npm install
```
### Setup 3: Deploy the Smart Contract
Set the private key:
```sh
export PRIVATE_KEY=<your private key>
```
Then
```shell
cd contract
forge install OpenZeppelin/openzeppelin-contracts --no-git
forge script script/Counter.s.sol:CounterScript --rpc-url <PHAROS_RPC_URL> --broadcast
```
### Setup 4: Build the Frontend
Connect the Frontend to the Smart Contract:
* Open `src/app.jsx` and replace its content with the following code:
```jsx
import React, { useState } from "react";
import { ethers } from "ethers";
const contractAddress = "YOUR_CONTRACT_ADDRESS"; // Replace with your contract address
const abi = [
{
"inputs": [],
"name": "get",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
];
function App() {
const [value, setValue] = useState("");
const [storedValue, setStoredValue] = useState("");
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(contractAddress, abi, signer);
const handleSet = async () => {
await contract.set(value);
alert("Value set!");
};
const handleGet = async () => {
const result = await contract.get();
setStoredValue(result.toString());
};
return (
<div>
<h1>Simple Storage dApp</h1>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Enter a value"
/>
<button onClick={handleSet}>Set Value</button>
<button onClick={handleGet}>Get Value</button>
<p>Stored Value: {storedValue}</p>
</div>
);
}
export default App;
```
Replace Placeholder Values
* Replace `YOUR_CONTRACT_ADDRESS` with the address of your deployed contract.
### Step 5: Run the dApp
Start the React App
* Navigate to the frontend directory and start the app:
```shell
npm start
```
Interact with the dApp:
* Open your browser and navigate to `http://localhost:3000`.
* Use the input field and buttons to interact with your smart contract.
### Troubleshooting
* Contract Deployment Fails: Ensure you have enough testnet tokens to cover the deployment cost.
* Frontend Connection Issues: Verify that the contract address and ABI are correct.
### Conclusion
Now that you’ve built your first end-to-end dApp.
This guide provides a comprehensive introduction to building and deploying an end-to-end dApp on the Pharos blockchain. If you encounter any issues, refer to the Troubleshooting section or consult the Pharos documentation. Happy building! 🚀
# Write Your First Token
This guide will walk you through the process of creating and deploying your first token on the Pharos blockchain. By the end of this guide, you will have a fully functional token contract and understand how to interact with it.
### Prerequisites
Before you begin, ensure you have the following:
* Git: Used for code management and obtain examples.
* Node.js: Install it from [nodejs.org](https://nodejs.org/).
* Pharos Devnet/Testnet Access: Access to a Pharos node (local or remote) for interacting with the blockchain.
### Setup 1: Install Foundry
* [Foundry](https://book.getfoundry.sh/getting-started/installation)
### Setup 2: Set Up the Project
Clone the example repo:
```shell
git clone https://github.com/PharosNetwork/examples
cd examples/token/foundry/contract
```
Install OpenZeppelin Contracts:
* Foundry uses forge to manage dependencies. Install OpenZeppelin contracts:
```shell
forge install OpenZeppelin/openzeppelin-contracts --no-git
```
### Setup 3: Write the Token Contract
Create a New Solidity File:
* Create a new file for your token contract:
```shell
touch src/Token.sol
```
Write the Token Contract:
* Open `src/Token.sol` in your favorite text editor and add the following code:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";
contract Token is ERC20 {
constructor(uint256 initialSupply) ERC20("Token", "MTK") {
_mint(msg.sender, initialSupply);
}
}
```
Compile the Smart Contract:
* Use forge to compile the contract:
```sh
forge build
```
Test the Smart Contract
* Use forge to test the contract:
```shell
forge test
```
### Step 4: Deploy the Token Contract
Create a Deployment Script:
* Create a new file for the deployment script:
```shell
touch script/DeployToken.s.sol
```
Write the Deployment Script:
* Open script/DeployToken.s.sol and add the following code:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "forge-std/Script.sol";
import "../src/Token.sol";
contract DeployToken is Script {
function run() external {
uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
v프로젝트로 돌아가기