Onionr/src/onionrstorage/setdata.py

71 lines
2.4 KiB
Python
Raw Normal View History

"""Onionr - Private P2P Communication.
Test Onionr as it is running
"""
import sys
import sqlite3
2020-03-26 08:57:54 +00:00
import onionrstorage
import onionrexceptions
import onionrcrypto as crypto
import filepaths
2020-11-02 01:31:11 +00:00
from onionrblocks import storagecounter, blockmetadata
2019-07-19 19:49:56 +00:00
from coredb import dbfiles
2020-11-02 01:31:11 +00:00
from onionrutils import bytesconverter
from etc.onionrvalues import DATABASE_LOCK_TIMEOUT
2020-10-15 09:50:52 +00:00
from onionrtypes import BlockHash
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
storage_counter = storagecounter.StorageCounter()
2020-03-26 08:57:54 +00:00
2022-01-06 20:48:22 +00:00
def set_data(data):
"""Set the data assciated with a hash."""
2019-06-22 22:54:41 +00:00
dataSize = sys.getsizeof(data)
2020-03-26 08:57:54 +00:00
nonce_hash = crypto.hashers.sha3_hash(
bytesconverter.str_to_bytes(
blockmetadata.fromdata.get_block_metadata_from_data(data)[2]))
nonce_hash = bytesconverter.bytes_to_str(nonce_hash)
2019-06-22 22:54:41 +00:00
if not type(data) is bytes:
data = data.encode()
2019-07-20 15:52:03 +00:00
dataHash = crypto.hashers.sha3_hash(data)
2019-06-22 22:54:41 +00:00
if type(dataHash) is bytes:
dataHash = dataHash.decode()
try:
2019-07-19 19:49:56 +00:00
onionrstorage.getData(dataHash)
2019-06-22 22:54:41 +00:00
except onionrexceptions.NoDataAvailable:
2022-01-06 20:48:22 +00:00
if storage_counter.add_bytes(dataSize):
onionrstorage.store(data, block_hash=dataHash)
conn = sqlite3.connect(
dbfiles.block_meta_db, timeout=DATABASE_LOCK_TIMEOUT)
2019-06-22 22:54:41 +00:00
c = conn.cursor()
2020-03-26 08:57:54 +00:00
c.execute(
"UPDATE hashes SET dataSaved=1 WHERE hash = ?;",
(dataHash,))
2019-06-22 22:54:41 +00:00
conn.commit()
conn.close()
2019-07-19 19:49:56 +00:00
with open(filepaths.data_nonce_file, 'a') as nonceFile:
nonceFile.write(nonce_hash + '\n')
2019-06-22 22:54:41 +00:00
else:
raise onionrexceptions.DiskAllocationReached
else:
2020-03-26 08:57:54 +00:00
raise onionrexceptions.DataExists(
"Data is already set for " + dataHash)
2019-06-22 22:54:41 +00:00
2019-09-27 23:04:49 +00:00
return dataHash