Зафиксировать текущие изменения CORE/CONTENT

This commit is contained in:
AidarKC
2026-11-29 18:16:49 +03:00
parent 3309cdb6ba
commit 09789fdf2f
103 changed files with 692 additions and 2182 deletions
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Offline: exact vectors and WS failure/restart; no paid or live calls."""
import asyncio
import base64
import csv
import importlib.util
import json
from pathlib import Path
import struct
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
P=ROOT/'tools/test-publisher'
sys.path.insert(0,str(P))
from core_content import sign_post,decode_stored_pair,find_channel_tail,require_namespace,NAMESPACE
def load(name,path):
spec=importlib.util.spec_from_file_location(name,path); mod=importlib.util.module_from_spec(spec); spec.loader.exec_module(mod); return mod
MODULES=[load(f'publisher{i}',p) for i,p in enumerate([P/'v1/publisher/publisher.py',P/'v2/publisher/publisher.py',P/'v2/publisher/publisher_multi.py'])]
with (ROOT/'docs/Blockchain/vectors/core-content-v1.tsv').open() as f:
FIX={row['name']:row for row in csv.DictReader(f,delimiter='\t')}
def packed(f):
c=bytes.fromhex(f['coreItem']); d=bytes.fromhex(f['contentItem']);return struct.pack('>I',len(c))+c+d
class PublisherTests(unittest.IsolatedAsyncioTestCase):
def test_exact_vectors(self):
f=FIX['post']; core=bytes.fromhex(f['core']); text=bytes.fromhex(f['content'])[9:].decode()
for mod in MODULES:
with self.subTest(mod=mod.__file__):
raw,digest=sign_post(mod.data_item,bytes(range(32)),core[1:33],2,1,1,core[117:149],text,struct.unpack_from('>q',core,37)[0])
self.assertEqual(raw,packed(f)); self.assertEqual(digest.hex(),f['coreHash'])
self.assertEqual(decode_stored_pair(base64.b64encode(raw).decode(),digest.hex()),(core,bytes.fromhex(f['content'])))
with self.assertRaises(ValueError): decode_stored_pair(base64.b64encode(raw[:-1]+bytes([raw[-1]^1])).decode(),digest.hex())
async def test_tail_global_not_ordinal(self):
by_num={struct.unpack_from('>i',bytes.fromhex(f['core']),33)[0]:f for f in FIX.values() if f['name']!='fork'}
async def fetch(cfg,n):
f=by_num[n];return f['coreHash'],base64.b64encode(packed(f)).decode()
n,h=await find_channel_tail(fetch,{'channel_root_block_number':1},3,FIX['channel']['coreHash'])
self.assertEqual(n,2);self.assertEqual(h.hex(),FIX['post']['coreHash'])
n,h=await find_channel_tail(fetch,{'channel_root_block_number':1},1,FIX['channel']['coreHash'])
self.assertEqual(n,1);self.assertEqual(h.hex(),FIX['channel']['coreHash'])
def test_reject_legacy_state(self):
with self.assertRaises(ValueError): require_namespace({'version':2})
async def test_single_and_multi_retry(self):
for i,mod in enumerate(MODULES):
with self.subTest(mod=mod.__file__), tempfile.TemporaryDirectory() as d:
base=Path(d); state_file=base/'state.json'; key=base/'key.json'; key.write_text(json.dumps(list(range(32)))); queue=base/'queue.json';queue.write_text('[{"text":"retry"}]')
cfg={'state_file':str(state_file),'key_file':str(key),'server_ws':'mock','blockchain_name':'mock','channel_name':'test','channel_root_block_number':1,'queue_file':str(queue),'min_interval_seconds':1,'max_interval_seconds':1}
root=FIX['channel']['coreHash']; h=FIX['post']['coreHash'];calls=[]
async def ws(url,op,payload,timeout=30):
calls.append(payload['blockBytesB64'])
if len(calls)==1: raise TimeoutError('simulated lost response')
return {'status':200}
state={'namespace':NAMESPACE,'last_block_number':2,'last_block_hash':h,'pending':None}
cs={'next_index':0,'last_line_block_number':2,'last_line_hash':h,'published_total':0}
if i==2: cfg['channels']=[dict(cfg)];state['channels']={'test':cs};publish=lambda s:mod.publish_channel(cfg,s,cfg['channels'][0],True)
else: state.update(cs);publish=lambda s:mod.publish_one(cfg,s,[{'text':'retry'}])
with patch.object(mod,'ws_call',ws):
with self.assertRaises(TimeoutError):await publish(state)
persisted=json.loads(state_file.read_text());self.assertIsNotNone(persisted['pending'])
await publish(persisted)
self.assertEqual(calls[0],calls[1]); self.assertIsNone(persisted['pending']);self.assertEqual(persisted['last_block_number'],3)
if __name__=='__main__': unittest.main(verbosity=2)