Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7e922337bc8a2fd7 • Your IP: Click to reveal 138.199.34.5 • Performance & security by Cloudflare
What is snapshot?
![]()
The term snapshot refers to the ability to record the state of something at a specific point in time. In blockchain, a snapshot refers to the act of recording the state of a blockchain, at a particular block height. In our case, it is used to record the total supply and balance of token holders at specific point in time.
Double spending problem
Double spending is a potential flaw in digital cash scheme in which the same digital token can be spent more than once. Since IRC2 tokens is basically a digital file it’s easier to duplicate than actual money. This means some people can manipulate their way to paying more than once with the same token. Here, the cryptocurrency is essentially stolen.
So, it’s obvious that we need to solve this issue. To avoid this, we implement snapshot mechanism in our IRC2 contract. The implementation can be found here, in odi-contracts repo of OpenDevICON.
Snapshot is used to avoid the double spending problem. This system runs the risk that many copies of the same bitstring are spent at different merchants. In naive implementation, it is possible to perform a “double spend” attack by reusing the same balance from different accounts.
The snapshot contract extends an IRC2 token with a snapshot mechanism. When a snapshot is created, the balances and total supply at the time are recorded for later access.
Snapshot are created by the internal _snapshot function, which will emit a snapshot event and set a snapshot id in the blockchain. balanceOfAt external method is used to get the balance of a addresss at particular snapshot id. Similarly, totalSupplyAt method is used to get the total supply at a particular snapshot id.
Snapshots are needed during transfer operation, mint operation and burn operation. When transferred, the snapshot of sending and recieving account needs to be updated. Similarly, during mint operation, the snapshot of address where the token was minted and the total supply needs to be changed. During burn operation, the snapshot of address where the token was burned from and the total supply needs to be changed.
Before diving deeper, let’s learn what these variables mean…
_current_snapshot_id : The current snapshot id. (VarDB)
_account_balance_snapshot: It is used to keep track of snapshot_id, and the account balance at that id. length is used to connect between them. Length is like the index of an array in this case. It is equivalent to 2 level 1 dicts combined.
Here, 0,1,2,3 i.e. the keys in both dicts are same, and they represent length. The values in ids represent snapshot id at that particular length, and values in vals represent balance at that particular length.
_total_supply_snapshot: It is used to keep track of total supply at a particular snapshot id. It works similar to account balance snapshot.
How does updating account snapshot work?
Here, first the current snapshot id is fetched and is set to current_id. Then, the balance of that account is set to current_value. The length, the key used to connect snapshot id with balance, is initialized to 1 when the contract is deployed. That value is set to length variable.
If length is 0, then, the snapshot balance of that account at length 0 is set to current_value, i.e. the balance of that account. Then, the length is increased. Generally, the length is not zero, and in this case, last_snapshot_id is set to the length-1.
Now, if the last_snapshot_id is less than current id, the snapshot id for that account at that length is set to current_id, value at that length is set to current_value and the length is updated by 1. Else, the value at length-1 is set to current_value.
How does updating total supply snapshot work?
This works similar to account snapshot update, except for balance of a particular address is replaced by total supply. Here, in DictDB, we don’t need additional depth for wallet address. The snapshot id is fetched, and length for total supply snapshot is fetched and set to local variables current_id and current_value respectively.
If length is 0, then, the snapshot total supply at length 0 is set to current_value, i.e. the total supply. Then, the length is increased. Generally, the length is not zero, and in this case, last_snapshot_id is set to the length -1.
Now, if the last_snapshot_id is less than current id, the snapshot id at that length is set to current_id, value at that length is set to current_value and the length is updated. Else, the value at length-1 is set to current_value.
Now, that updating account and total supply snapshot are covered, let’s see how we can get the balance of a account or total supply at a particular snapshot.
balanceOfAt
This method is used to find the balance of a particular account at a particular snapshot id. The snapshot id starts at 0 and is updated by 1. So, it cannot be less than 0.
When a valid snapshot id is queried, there are the following possibilties:
— The queried value was modified after the snapshot was taken.
— The value was not modified after the snapshot was taken.
— More snapshot ids were created after the requested one.
So, basically we need to find the balance at that id.
Here, we initialize low as 0 and high as the length.
While, the low value is less than high, we calculate mid by integer division of low and high. Then the id of that account when length = mid is fetched. If it is greater than snapshot id, high is set to mid. Else, low is set to mid + 1. This continues till the condition low is less than high is false.
Then, if the queried snapshot id is equal to the 0 length, then that value at 0 length is returned.
If low is equal to 0, 0 is returned, i.e. balance at that snapshot id is zero.
Else, the balance of that account at length `low-1` is returned.
This can be a bit complex to understand. It can be simplified by the following code snippet for understanding.
Here, the keys in the dictionaries, indicate length. The value in dict ids represent snapshot id, equivalent to
_account_balance_snapshot[_account][‘ids’][length] in the code. The value in vals represent balance at that length, equivalent to
account_balance_snapshot[_account][‘values’][length] in the code.
Note that, the initial length is set to 1 in on_install method. So, in the above snippet, we use vals[low] only, in the last line.
totalSupplyAt
This method is used to find the total supply at a particular snapshot id. The snapshot id cannot be less than 0.
This works exactly similar to the balanceOfAt method, except the total supply value is fetched instead of balance of particular account.
Overview
Snapshots are a copy of the blockchain at a particular point in time. Snapshots can help newer users to get into sync faster than syncing from 0.
Issues
- Snapshots are not validated by the wallet.
- Snapshots are an inherently centralised method of getting into sync.
- Users may mistakenly install a malicious or corrupted snapshot. If enough users install the bad snapshot then the integrity of the chain could be compromised.
Using snapshots
In the Wallet
Snapshots can now be downloaded and applied automatically by the wallet.
It is accessible from File -> Snapshot Download or the -snapshotdownload startup option
Manual method
Creating your own snapshot
- Shutdown your wallet.
- Create an empty archive in an archive program of your choice.
- Add all the blk****.dat files to your archive.
- Add the txleveldb folder to your archive.
- When you want to use it, follow the manual method but with your archive.
Alternatives
This is preferred. With all of the recent changes in the wallet it is only mildly slower than using a snapshot. This doesn’t require trust in the snapshot creator.
As of April 2021 these are no longer offered. It doesn’t bypass the checks in the wallet which prevent malicious bootstraps from damaging the chain. There is little to no point in using one of these over syncing from 0. It brings limited speed benefits compared to syncing normally but relies on a centralised download.
Разбираемся в снепшотах в контексте криптовалют
Снепшот (Snapshot) — это документирование состояния блокчейна на определенной отметке высоты блока.
Что такое снепшот?
Способность записывать состояние чего-либо в точный момент времени называется снапшотом. В мире блокчейна снапшот — это акт документирования состояния блокчейна на определенной высоте блока. Его используют для отслеживания общего количества и баланса держателей токенов в любой момент времени.
Традиционная интерпретация.
Получение снапшота, также известного как снапшот хранилища, аналогично фотографированию данных вашего сервера в определенный момент времени. Снапшоты не являются полным дубликатом данных на жестком диске; по большей части они представляют собой метаданные, определяющие состояние информации. Кроме того, они могут быть сохранены только на локальном сервере или устройстве, где они были созданы.
Так как при тестировании приложений живые данные, например, при тестировании нового приложения или программы или опробовании новых настроек, могут подвергнуть вашу систему риску, для test/dev обычно используются снапшоты. Они предоставляют доступ к бесконечному количеству клонов ваших данных, что дает вам возможность работать над разработкой без ущерба для вашей обычной работы. Автоматизация, тестирование, итерации и демонтаж рабочих процессов не занимают много дополнительного места в хранилище. При возникновении ошибки можно откатить сервер к более ранней точке.
Полное резервное копирование может занимать несколько часов, а в некоторых случаях его приходится делать в течение ночи, поскольку оно требует больших системных ресурсов. А вот моментальные снимки могут быть созданы за несколько секунд и так часто, как это необходимо. Кроме того, можно дедуплицировать данные, создаваемые с помощью моментальных снимков, используя такие технологии, как отслеживание модифицированных блоков (CBT).
Снапшоты предназначены для хранения только в течение ограниченного периода времени, но при неправильной работе они могут привести к невероятно сложным цепочкам данных и очень длительному времени консолидации.
Криптографические снепшоты.
Снапшот в криптовалюте — это протокол состояния блокчейна на определенной высоте блока. Он фиксирует весь блокчейн, включая все существующие адреса и связанные с ними данные.
Что такое снепшоты в криптовалютных эйрдроп-событиях?
Перед проведением каждого раунда события airdrop часто делаются моментальные снимки. Распределение токенов происходит на основе баланса каждого адреса блокчейна, доступного в период моментального снимка. Снимки делаются для того, чтобы зафиксировать баланс каждого держателя токенов в определенный момент времени (т.е. высоту блока). Пользователи обычно могут перемещать свои средства после получения моментального снимка, не ставя под угрозу свое право на участие в данном раунде выплат.