diff --git a/bitassets/pubspec.yaml b/bitassets/pubspec.yaml index 606ff75b79..3b0969535d 100644 --- a/bitassets/pubspec.yaml +++ b/bitassets/pubspec.yaml @@ -2,7 +2,7 @@ name: bitassets description: UI for Drivechain (BIP300/301) based sidechains publish_to: "none" # Remove this line if you wish to publish to pub.dev -version: 1.0.398 +version: 1.0.399 environment: sdk: 3.13.7 diff --git a/bitnames/pubspec.yaml b/bitnames/pubspec.yaml index 1eef131349..4176c23743 100644 --- a/bitnames/pubspec.yaml +++ b/bitnames/pubspec.yaml @@ -2,7 +2,7 @@ name: bitnames description: UI for Drivechain (BIP300/301) based sidechains publish_to: "none" # Remove this line if you wish to publish to pub.dev -version: 1.0.399 +version: 1.0.400 environment: sdk: 3.13.7 diff --git a/bitwindow/lib/main.dart b/bitwindow/lib/main.dart index 66e0165f96..ce06df9567 100644 --- a/bitwindow/lib/main.dart +++ b/bitwindow/lib/main.dart @@ -58,6 +58,7 @@ import 'package:bitwindow/widgets/address_list.dart'; import 'package:bitwindow/widgets/backend_swap.dart'; import 'package:bitwindow/widgets/datadir_network_notice.dart'; import 'package:bitwindow/widgets/ecash_upgrade_banner.dart'; +import 'package:bitwindow/widgets/coinnews_window.dart'; import 'package:bitwindow/widgets/converter_window.dart'; import 'package:bitwindow/widgets/hash_calculator_modal.dart'; // App shell needs MaterialApp + ThemeData; Colors/Scaffold serve the @@ -816,6 +817,9 @@ const _subWindowAccent = Color.fromARGB(255, 255, 153, 0); case SubWindowTypes.bitDriveId: child = const BitDriveTab(); break; + case SubWindowTypes.coinNewsId: + child = CoinNewsWindow(story: arguments['story'] as String?); + break; } return (title: '$windowTitle | Bitwindow', child: child, work: work); @@ -1631,6 +1635,14 @@ class SubWindowTypes { defaultSize: Size(1000, 700), defaultPosition: Offset(150, 150), ); + + static const String coinNewsId = 'coin_news'; + static var coinNews = SailWindow( + identifier: coinNewsId, + name: 'Coin News', + defaultSize: Size(760, 720), + defaultPosition: Offset(200, 120), + ); } List initalBinaries() { @@ -1704,6 +1716,8 @@ Widget inAppWindowPage( return const MultisigLoungeTab(); case SubWindowTypes.bitDriveId: return const BitDriveTab(); + case SubWindowTypes.coinNewsId: + return CoinNewsWindow(story: arguments['story'] as String?); } return SailCard( title: 'Unknown window type: $windowType', diff --git a/bitwindow/lib/widgets/coinnews.dart b/bitwindow/lib/widgets/coinnews.dart index 77b23d73d1..5e7fedfcbd 100644 --- a/bitwindow/lib/widgets/coinnews.dart +++ b/bitwindow/lib/widgets/coinnews.dart @@ -3,17 +3,14 @@ import 'dart:convert'; import 'dart:math'; import 'package:bitwindow/env.dart'; +import 'package:bitwindow/main.dart'; import 'package:bitwindow/pages/overview_page.dart'; -import 'package:bitwindow/providers/blockchain_provider.dart'; import 'package:bitwindow/providers/news_provider.dart'; -import 'package:bitwindow/utils/error_text.dart'; import 'package:bitwindow/utils/explorer_url.dart'; -import 'package:bitwindow/utils/web_link.dart'; -import 'package:bitwindow/widgets/news_cost.dart'; +import 'package:bitwindow/widgets/coinnews_window.dart'; import 'package:bitwindow/widgets/pagination.dart'; import 'package:collection/collection.dart'; import 'package:flutter/widgets.dart'; -import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart' show Intl; import 'package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart'; @@ -1106,452 +1103,9 @@ class CoinNewsTable extends StatelessWidget { } } -/// Opens [news] as a panel at the right edge of the window; a phone shows it as a bottom sheet. +/// Opens [news] in the Coin News window. void showCoinNewsArticle(BuildContext context, CoinNews news) { - if (SailStyleValues.phoneLayout(context)) { - unawaited( - showSailSheet( - context: context, - side: SailSheetSide.bottom, - size: MediaQuery.of(context).size.height * 0.95, - builder: (context) => CoinNewsArticlePanel(news: news, onClose: () async => Navigator.of(context).pop()), - ), - ); - return; - } - unawaited( - showSailSidePanel( - context, - (context, close) => SizedBox( - width: SailSidePanel.width, - child: CoinNewsArticlePanel(news: news, onClose: close), - ), - ), - ); -} - -class CoinNewsArticlePanel extends StatefulWidget { - final CoinNews news; - final Future Function() onClose; - - const CoinNewsArticlePanel({super.key, required this.news, required this.onClose}); - - @override - State createState() => _CoinNewsArticlePanelState(); -} - -class _CoinNewsArticlePanelState extends State { - BitwindowRPC get api => GetIt.I.get(); - NewsProvider get _newsProvider => GetIt.I.get(); - final BlockchainProvider _blockchain = GetIt.I.get(); - final FormatterProvider _formatter = GetIt.I.get(); - - List _comments = []; - bool _loading = true; - bool _posting = false; - String? _loadError; - String? _postError; - String? _replyTo; // item_id being replied to; null = top-level - int _reads = 0; - final TextEditingController _controller = TextEditingController(); - - /// The newest read of the story. A story in the mempool gets its block time and item ID from a later read. - late CoinNews _story = _newest() ?? widget.news; - - String get _itemId => _story.itemId; - - @override - void initState() { - super.initState(); - _newsProvider.addListener(_onNews); - _blockchain.addListener(_load); - _blockchain.recentChanged.addListener(_load); - _load(); - } - - @override - void dispose() { - _newsProvider.removeListener(_onNews); - _blockchain.removeListener(_load); - _blockchain.recentChanged.removeListener(_load); - _controller.dispose(); - super.dispose(); - } - - CoinNews? _newest() { - final txid = widget.news.txid; - if (txid.isEmpty) { - return null; - } - return _newsProvider.news.firstWhereOrNull((n) => n.txid == txid && n.vout == widget.news.vout); - } - - void _onNews() { - final story = _newest(); - if (story == null || story == _story) { - return; - } - final itemChanged = story.itemId != _itemId; - setState(() => _story = story); - if (itemChanged) { - unawaited(_load()); - } - } - - /// Reads the thread. Only the newest read changes the panel. - Future _load() async { - final read = ++_reads; - if (_itemId.isEmpty) { - setState(() { - _comments = []; - _replyTo = null; - _loadError = null; - _loading = false; - }); - return; - } - List? comments; - String? error; - try { - final response = await api.misc.listComments(_itemId); - comments = response.comments; - error = response.indexerError.isEmpty ? null : errorText('could not list comments: ${response.indexerError}'); - } catch (e) { - error = errorText(e); - } - if (!mounted || read != _reads) { - return; - } - setState(() { - _comments = comments ?? _comments; - _loadError = error; - _loading = false; - }); - } - - Future _post() async { - final body = _controller.text.trim(); - if (body.isEmpty || _posting) { - return; - } - if (!await NewsCost.confirmFirstComment(context, body: body)) { - return; - } - if (!mounted) { - return; - } - setState(() { - _posting = true; - _postError = null; - }); - try { - await api.misc.commentNews(_replyTo ?? _itemId, body); - if (!mounted) { - return; - } - _controller.clear(); - setState(() => _replyTo = null); - await _load(); - } catch (e) { - if (!mounted) { - return; - } - setState(() => _postError = errorText(e)); - } finally { - if (mounted) { - setState(() => _posting = false); - } - } - } - - @override - Widget build(BuildContext context) { - final current = SailTheme.of(context); - final opposite = current.isLightMode() ? SailThemeData.darkTheme : SailThemeData.lightTheme; - - return SailTheme( - data: opposite(current.colors.primary, current.dense, current.font, current.style), - child: Builder( - builder: (context) { - final theme = SailTheme.of(context); - - return DecoratedBox( - decoration: theme.chrome.panel(theme.colors), - child: Padding( - padding: const EdgeInsets.all(SailStyleValues.padding16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Expanded( - child: SelectionArea( - child: SingleChildScrollView( - child: SailColumn( - spacing: SailStyleValues.padding12, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _head(context), - if (_story.url.isNotEmpty) _link(context), - if (_story.content.isNotEmpty) _body(context), - Container(height: 1, color: theme.colors.divider), - ListenableBuilder( - listenable: _formatter, - builder: (context, _) => _commentsThread(context), - ), - ], - ), - ), - ), - ), - if (_itemId.isNotEmpty) _composerFooter(context), - ], - ), - ), - ); - }, - ), - ); - } - - Widget _head(BuildContext context) { - final theme = SailTheme.of(context); - return Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: SailColumn( - spacing: SailStyleValues.padding04, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SailText.primary18(_story.headline, bold: true), - ListenableBuilder( - listenable: _newsProvider, - builder: (context, _) => SailText.secondary12( - storyMeta( - _story, - topicName: _newsProvider.topicName(_story.topic), - date: storyTime(_story, formatDate), - separator: ' · ', - ), - color: theme.colors.textSecondary, - ), - ), - ], - ), - ), - const SizedBox(width: SailStyleValues.padding08), - SailIconBoxButton(icon: SailSVGAsset.x, tooltip: 'Close', onPressed: widget.onClose), - ], - ); - } - - Widget _link(BuildContext context) { - return _StoryLink(text: _story.url, link: webLink(_story.url)); - } - - Widget _body(BuildContext context) { - final theme = SailTheme.of(context); - final text = SailStyleValues.fourteen.copyWith(color: theme.colors.text, fontFamily: theme.chrome.textFamily()); - return MarkdownBody( - data: _story.content, - styleSheet: MarkdownStyleSheet( - p: text, - a: text.copyWith(color: theme.colors.info), - h1: SailStyleValues.eighteen.copyWith(color: theme.colors.text, fontFamily: theme.chrome.textFamily()), - h2: SailStyleValues.sixteen.copyWith(color: theme.colors.text, fontFamily: theme.chrome.textFamily()), - h3: text.copyWith(fontWeight: SailStyleValues.boldWeight), - listBullet: text, - blockquoteDecoration: BoxDecoration( - color: theme.colors.backgroundSecondary, - borderRadius: theme.chrome.radius, - ), - codeblockDecoration: BoxDecoration( - color: theme.colors.backgroundSecondary, - borderRadius: theme.chrome.radius, - ), - code: SailStyleValues.thirteen.copyWith( - color: theme.colors.text, - fontFamily: SailFonts.mono, - backgroundColor: theme.colors.backgroundSecondary, - ), - codeblockPadding: const EdgeInsets.all(SailStyleValues.padding12), - ), - sizedImageBuilder: (image) => _StoryLink( - text: (image.alt ?? '').isEmpty ? image.uri.toString() : image.alt!, - link: webLink(image.uri.toString()), - ), - onTapLink: (_, href, _) async { - final link = href == null ? null : webLink(href); - if (link == null) { - return; - } - await openUrl(link); - }, - ); - } - - /// The comment thread (spec §7). Replies nest under their parent; - /// siblings are ordered by fee, highest first. - Widget _commentsThread(BuildContext context) { - final theme = SailTheme.of(context); - final roots = _comments.where((c) => c.parentId == _itemId).toList(); - - return SailColumn( - spacing: SailStyleValues.padding12, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - SailText.primary15('Comments (${_comments.length})', bold: true), - if (_loadError != null) SailText.secondary12(_loadError!, color: theme.colors.error), - if (_itemId.isEmpty) - SailText.secondary12('Comments open when the story is in a block.') - else if (_loading) - SailText.secondary12('Loading comments…') - else if (roots.isEmpty && _loadError == null) - SailText.secondary12('No comments yet. Be the first.') - else - Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [for (final root in roots) ..._commentTree(context, root, depth: 0)], - ), - ], - ); - } - - /// Deeper replies keep this indent, so a long thread stays readable in the panel. - static const _maxIndent = 5; - - List _commentTree(BuildContext context, Comment comment, {required int depth}) => [ - Padding( - padding: EdgeInsets.only(left: SailStyleValues.padding16 * min(depth, _maxIndent)), - child: _commentTile(context, comment), - ), - for (final reply in _comments.where((c) => c.parentId == comment.itemId)) - ..._commentTree(context, reply, depth: depth + 1), - ]; - - Widget _commentTile(BuildContext context, Comment comment) { - final theme = SailTheme.of(context); - final meta = [ - _shortAuthor(comment.author), - comment.pending ? 'Pending' : formatDate(comment.createTime.toDateTime()), - // The server sends 0 for a fee that it does not know. - if (comment.feeSats > 0) _formatter.formatSats(comment.feeSats.toInt()), - ].join(' · '); - return DecoratedBox( - decoration: BoxDecoration( - border: Border(bottom: BorderSide(color: theme.colors.divider)), - ), - child: Padding( - padding: const EdgeInsets.symmetric(vertical: SailStyleValues.padding08), - child: SailColumn( - spacing: SailStyleValues.padding04, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SailText.secondary12(meta, color: theme.colors.textSecondary), - SailText.primary13(comment.body, overflow: TextOverflow.visible), - if (comment.url.isNotEmpty) SailText.secondary12(comment.url, color: theme.colors.textSecondary), - // A reply in a block before its parent is not valid, so it waits for the block of the parent. - if (!comment.pending) - _TextAction( - label: _replyTo == comment.itemId ? 'Cancel reply' : 'Reply', - onTap: () => setState(() => _replyTo = _replyTo == comment.itemId ? null : comment.itemId), - ), - ], - ), - ), - ); - } - - String _shortAuthor(String author) => author.length > 10 ? '${author.substring(0, 10)}…' : author; - - /// Pinned composer at the bottom of the panel so posting the first - /// comment never requires scrolling past the article. Tapping a - /// comment's Reply re-targets this same box; otherwise it posts a - /// top-level comment. - Widget _composerFooter(BuildContext context) { - final theme = SailTheme.of(context); - final replyParent = _comments.firstWhereOrNull((c) => c.itemId == _replyTo); - - return DecoratedBox( - decoration: BoxDecoration( - border: Border(top: BorderSide(color: theme.colors.divider)), - ), - child: Padding( - padding: const EdgeInsets.only(top: SailStyleValues.padding12), - child: SailColumn( - spacing: SailStyleValues.padding08, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (replyParent != null) - Row( - children: [ - Expanded( - child: SailText.secondary12( - 'Replying to ${_shortAuthor(replyParent.author)}', - color: theme.colors.textTertiary, - ), - ), - _TextAction(label: 'Cancel', onTap: () => setState(() => _replyTo = null)), - ], - ), - SailTextField(hintText: _replyTo != null ? 'Write a reply…' : 'Add a comment…', controller: _controller), - if (_postError != null) SailText.secondary12(_postError!, color: theme.colors.error), - NewsCostTooltip( - action: NewsAction.NEWS_ACTION_COMMENT, - body: _controller, - child: SailButton(label: 'Comment', loading: _posting, onPressed: () async => _post()), - ), - ], - ), - ), - ); - } -} - -/// A link of a story. A null [link] shows [text] with no action. -class _StoryLink extends StatelessWidget { - final String text; - final Uri? link; - - const _StoryLink({required this.text, required this.link}); - - @override - Widget build(BuildContext context) { - final theme = SailTheme.of(context); - final link = this.link; - if (link == null) { - return SailText.secondary12(text, color: theme.colors.textSecondary); - } - return MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( - onTap: () async => openUrl(link), - child: SailText.secondary12(text, color: theme.colors.info), - ), - ); - } -} - -/// A short action as a text link, under a comment or next to a line. -class _TextAction extends StatelessWidget { - final String label; - final VoidCallback onTap; - - const _TextAction({required this.label, required this.onTap}); - - @override - Widget build(BuildContext context) { - final theme = SailTheme.of(context); - return SailTappable( - onTap: () async => onTap(), - borderRadius: theme.chrome.radiusSmall, - child: SailText.primary12(label, bold: true, color: theme.colors.info), - ); - } + unawaited(GetIt.I.get().open(SubWindowTypes.coinNews, arguments: {'story': storyKey(news)})); } /// The body of a Coin News card, in place of its stories, when the user subscribes to no topic. diff --git a/bitwindow/lib/widgets/coinnews_window.dart b/bitwindow/lib/widgets/coinnews_window.dart new file mode 100644 index 0000000000..38d7917372 --- /dev/null +++ b/bitwindow/lib/widgets/coinnews_window.dart @@ -0,0 +1,1002 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:bitwindow/pages/overview_page.dart'; +import 'package:bitwindow/providers/blockchain_provider.dart'; +import 'package:bitwindow/providers/news_provider.dart'; +import 'package:bitwindow/utils/error_text.dart'; +import 'package:bitwindow/utils/explorer_url.dart'; +import 'package:bitwindow/utils/web_link.dart'; +import 'package:bitwindow/widgets/coinnews.dart'; +import 'package:bitwindow/widgets/fee_coinnews.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; +import 'package:intl/intl.dart'; +import 'package:sail_ui/sail_ui.dart'; + +/// The emoji that a reaction can carry. +const reactionEmoji = ['👍', '👎', '💯', '😂', '🔥']; + +const _paper = Color(0xffffffff); +const _ink = Color(0xff000000); +const _linkBlue = Color(0xff0000ee); +const _readGrey = Color(0xff808080); +const _metaGrey = Color(0xff404040); + +TextStyle _text({double size = 14, bool bold = false, Color color = _ink, bool underline = false}) => TextStyle( + fontFamily: SailFonts.mono, + fontSize: size, + height: 1.45, + fontWeight: bold ? FontWeight.bold : FontWeight.normal, + color: color, + decoration: underline ? TextDecoration.underline : null, + decorationColor: color, +); + +String _time(DateTime time) => DateFormat('yyyy-MM-dd HH:mm').format(time.toLocal()); + +/// The ids of the stories that the user opened. +class ReadStoriesSetting extends SettingValue> { + ReadStoriesSetting({super.newValue}); + + /// The most ids the setting keeps; the oldest go first. + static const limit = 1000; + + @override + String get key => 'coin_news_read_stories'; + + @override + List defaultValue() => const []; + + @override + List? fromJson(String jsonString) => (jsonDecode(jsonString) as List).cast(); + + @override + String toJson() => jsonEncode(value); + + @override + SettingValue> withValue([List? value]) => ReadStoriesSetting(newValue: value); +} + +/// True once the user turns off the warning before a story link opens. +class LinkWarningOffSetting extends SettingValue { + LinkWarningOffSetting({super.newValue}); + + @override + String get key => 'coin_news_link_warning_off'; + + @override + bool defaultValue() => false; + + @override + bool? fromJson(String jsonString) => jsonString == 'true'; + + @override + String toJson() => value.toString(); + + @override + SettingValue withValue([bool? value]) => LinkWarningOffSetting(newValue: value); +} + +/// Gives [child] the Windows 95 look, whatever the theme of the app. +class Win95 extends StatelessWidget { + final Widget child; + + const Win95({super.key, required this.child}); + + @override + Widget build(BuildContext context) { + final theme = SailTheme.of(context); + return SailTheme( + data: SailThemeData.lightTheme(theme.colors.primary, theme.dense, theme.font, SailThemeStyle.win95), + child: child, + ); + } +} + +/// The key of [news] in the window arguments and the read list. +String storyKey(CoinNews news) => news.itemId.isNotEmpty ? news.itemId : '${news.txid}:${news.vout}'; + +/// Coin News in its own window: the stories of one topic, highest fee first, and one story with its comments. +class CoinNewsWindow extends StatefulWidget { + /// The story to open first, by [storyKey]. + final String? story; + + const CoinNewsWindow({super.key, this.story}); + + @override + State createState() => _CoinNewsWindowState(); +} + +class _CoinNewsWindowState extends State { + final _settings = GetIt.I.get(); + final _topicSetting = FeeTopicSetting('coin_news_window_topic'); + NewsProvider get _news => GetIt.I.get(); + + String? _topic; + String? _open; + List _read = const []; + + @override + void initState() { + super.initState(); + _open = widget.story; + _news.addListener(_changed); + unawaited(_load()); + } + + @override + void dispose() { + _news.removeListener(_changed); + super.dispose(); + } + + void _changed() { + if (mounted) { + setState(() {}); + } + } + + Future _load() async { + final topic = (await _settings.getValue(_topicSetting)).value; + final read = (await _settings.getValue(ReadStoriesSetting())).value; + if (!mounted) { + return; + } + setState(() { + _topic = topic.isEmpty ? null : topic; + _read = read; + }); + final open = _open; + if (open != null) { + await _markRead(open); + } + } + + Future _markRead(String key) async { + if (_read.contains(key)) { + return; + } + final read = [..._read, key]; + final kept = read.sublist(read.length > ReadStoriesSetting.limit ? read.length - ReadStoriesSetting.limit : 0); + setState(() => _read = kept); + await _settings.setValue(ReadStoriesSetting(newValue: kept)); + } + + Future _openStory(CoinNews news) async { + setState(() => _open = storyKey(news)); + await _markRead(storyKey(news)); + } + + Future _pickTopic(String? topic) async { + if (topic == null) { + return; + } + setState(() => _topic = topic); + await _settings.setValue(_topicSetting.withValue(topic)); + } + + @override + Widget build(BuildContext context) { + final open = _open; + final story = open == null + ? null + : _news.news.firstWhereOrNull((n) => n.itemId == open || (n.txid.isNotEmpty && '${n.txid}:${n.vout}' == open)); + return Win95( + child: Builder( + builder: (context) => ColoredBox( + color: SailTheme.of(context).colors.background, + child: Padding( + padding: const EdgeInsets.all(4), + child: open == null + ? _FeedPage( + topics: _news.topics, + topic: _currentTopic(), + stories: _stories(), + read: _read, + error: _news.readError, + onTopic: _pickTopic, + onStory: _openStory, + ) + : story == null + ? _MissingStory(onBack: () => setState(() => _open = null)) + : CoinNewsStoryPage( + key: ValueKey(open), + story: story, + topicName: _news.topicName(story.topic), + onBack: () => setState(() => _open = null), + ), + ), + ), + ), + ); + } + + Topic? _currentTopic() { + final topics = _news.topics; + return topics.firstWhereOrNull((t) => t.topic == _topic) ?? topics.firstOrNull; + } + + List _stories() { + final topic = _currentTopic(); + if (topic == null) { + return const []; + } + return _news.currentNews.where((n) => n.topic == topic.topic).toList(); + } +} + +class _FeedPage extends StatelessWidget { + final List topics; + final Topic? topic; + final List stories; + final List read; + final String? error; + final Future Function(String?) onTopic; + final Future Function(CoinNews) onStory; + + const _FeedPage({ + required this.topics, + required this.topic, + required this.stories, + required this.read, + required this.error, + required this.onTopic, + required this.onStory, + }); + + @override + Widget build(BuildContext context) { + final topic = this.topic; + final error = this.error; + final days = topic?.retentionDays ?? 0; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _Toolbar( + children: [ + SailText.primary13('Topic:'), + SizedBox( + width: 200, + child: SailDropdownButton( + value: topic?.topic, + hint: 'No topic', + items: [for (final t in topics) SailDropdownItem(value: t.topic, label: t.name)], + onChanged: (value) => unawaited(onTopic(value)), + ), + ), + const Spacer(), + SailButton( + label: 'Broadcast…', + variant: ButtonVariant.secondary, + skipLoading: true, + onPressed: () => displayBroadcastNewsDialog(context), + ), + ], + ), + Expanded( + child: _Paper( + children: [ + Row( + children: [ + Expanded(child: Text(topic?.name ?? 'Coin News', style: _text(size: 18, bold: true))), + Text('sorted by fee', style: _text(size: 12, color: _readGrey)), + ], + ), + const Divider(color: _ink, height: 1, thickness: 1), + if (error != null) Text(error, style: _text(size: 12)), + if (stories.isEmpty && error == null) Text('No stories in this topic.', style: _text(size: 13)), + for (final story in stories) + _FeedRow(story: story, read: read.contains(storyKey(story)), onTap: () => onStory(story)), + ], + ), + ), + _StatusBar( + cells: [ + '${stories.length} ${stories.length == 1 ? 'story' : 'stories'}', + days == 0 ? 'All stories' : 'Last $days ${days == 1 ? 'day' : 'days'}', + ], + ), + ], + ); + } +} + +class _FeedRow extends StatelessWidget { + final CoinNews story; + final bool read; + final Future Function() onTap; + + const _FeedRow({required this.story, required this.read, required this.onTap}); + + @override + Widget build(BuildContext context) { + final domain = webLink(story.url)?.host; + final color = read ? _readGrey : _linkBlue; + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 150, + child: Text(formatSatoshis(story.feeSats.toInt()), style: _text(), textAlign: TextAlign.right), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text.rich( + TextSpan( + children: [ + WidgetSpan( + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: () => unawaited(onTap()), + child: Text(story.headline, style: _text(color: color, underline: true)), + ), + ), + ), + if (domain != null) + TextSpan( + text: ' ($domain)', + style: _text(color: _readGrey), + ), + ], + ), + ), + Text(storyTime(story, _time), style: _text(size: 12, color: _metaGrey)), + ], + ), + ), + ], + ); + } +} + +class _MissingStory extends StatelessWidget { + final VoidCallback onBack; + + const _MissingStory({required this.onBack}); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _Toolbar(children: [_BackButton(onBack: onBack)]), + Expanded( + child: _Paper(children: [Text('This story is not in the news list.', style: _text())]), + ), + ], + ); + } +} + +/// One story with its reactions and comments, and a form to comment. +class CoinNewsStoryPage extends StatefulWidget { + final CoinNews story; + final String? topicName; + final VoidCallback onBack; + + const CoinNewsStoryPage({super.key, required this.story, required this.topicName, required this.onBack}); + + @override + State createState() => _CoinNewsStoryPageState(); +} + +class _CoinNewsStoryPageState extends State { + MiscAPI get _api => GetIt.I.get().misc; + final _blockchain = GetIt.I.get(); + + final _body = TextEditingController(); + late final _fee = TextEditingController(text: '${widget.story.feeSats}'); + + List _comments = const []; + String? _loadError; + String? _postError; + bool _posting = false; + int _reads = 0; + + @override + void initState() { + super.initState(); + _body.addListener(_changed); + _fee.addListener(_changed); + _blockchain.addListener(_reload); + _blockchain.recentChanged.addListener(_reload); + _reload(); + } + + @override + void didUpdateWidget(CoinNewsStoryPage old) { + super.didUpdateWidget(old); + if (old.story.itemId != widget.story.itemId) { + _reload(); + } + } + + @override + void dispose() { + _blockchain.removeListener(_reload); + _blockchain.recentChanged.removeListener(_reload); + _body.dispose(); + _fee.dispose(); + super.dispose(); + } + + void _changed() => setState(() {}); + + void _reload() => unawaited(_loadComments()); + + Future _loadComments() async { + final read = ++_reads; + if (widget.story.itemId.isEmpty) { + setState(() { + _comments = const []; + _loadError = null; + }); + return; + } + String? error; + var comments = _comments; + try { + final response = await _api.listComments(widget.story.itemId); + comments = response.comments.sorted((a, b) => b.feeSats.compareTo(a.feeSats)); + error = response.indexerError.isEmpty ? null : errorText(response.indexerError); + } catch (e) { + error = errorText(e); + } + if (!mounted || read != _reads) { + return; + } + setState(() { + _comments = comments; + _loadError = error; + }); + } + + int? get _feeSats => int.tryParse(_fee.text.trim()); + + int get _length => _body.text.trim().runes.length; + + /// Why the comment cannot go out, or null when it can. + String? get _refusal { + final fee = _feeSats; + final min = widget.story.feeSats.toInt(); + if (fee == null || fee < min) { + return 'The fee must be ${formatSatoshis(min)} or more.'; + } + if (_length > widget.story.maxCommentChars) { + return 'The comment is longer than the story.'; + } + return null; + } + + Future _post() async { + final fee = _feeSats; + if (fee == null || _refusal != null) { + return; + } + setState(() { + _posting = true; + _postError = null; + }); + try { + await _api.commentNews(widget.story.itemId, _body.text.trim(), feeSats: fee); + _body.clear(); + await _loadComments(); + } catch (e) { + if (mounted) { + setState(() => _postError = errorText(e)); + } + } finally { + if (mounted) { + setState(() => _posting = false); + } + } + } + + Future _react([String? emoji]) async { + await showThemedDialog( + context: context, + builder: (_) => Win95( + child: ReactionDialog(story: widget.story, emoji: emoji ?? reactionEmoji.first), + ), + ); + } + + @override + Widget build(BuildContext context) { + final story = widget.story; + final link = webLink(story.url); + final canComment = story.itemId.isNotEmpty; + final refusal = _body.text.trim().isEmpty ? null : _refusal; + final postError = _postError; + final loadError = _loadError; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _Toolbar(children: [_BackButton(onBack: widget.onBack)]), + Expanded( + child: _Paper( + children: [ + SelectableText(story.headline, style: _text(size: 20, bold: true)), + Text.rich( + TextSpan( + style: _text(size: 12, color: _metaGrey), + children: [ + TextSpan( + text: + '${formatSatoshis(story.feeSats.toInt())} · ' + '${storyMeta(story, topicName: widget.topicName, date: storyTime(story, _time))}', + ), + if (story.txid.length > 8) ...[ + const TextSpan(text: ' · txid '), + WidgetSpan( + child: _Link( + text: '${story.txid.substring(0, 4)}…${story.txid.substring(story.txid.length - 4)}', + size: 12, + onTap: () => + openUrl(Uri.parse(mempoolTxUrl(story.txid, GetIt.I.get().network))), + ), + ), + ], + ], + ), + ), + if (link != null) + _Link(text: link.toString(), onTap: () => openStoryLink(context, link)) + else if (story.url.isNotEmpty) + SelectableText(story.url, style: _text(color: _metaGrey)), + if (story.content.isNotEmpty) SelectableText(story.content, style: _text()), + if (canComment) + Wrap( + spacing: 6, + runSpacing: 6, + children: [ + for (final r in story.reactions) + SailButton( + label: '${r.emoji} ${formatSatoshis(r.feeSats.toInt())}', + variant: ButtonVariant.secondary, + skipLoading: true, + onPressed: () => _react(r.emoji), + ), + SailButton(label: '+', variant: ButtonVariant.secondary, skipLoading: true, onPressed: _react), + ], + ), + const Divider(color: _ink, height: 1, thickness: 1), + Row( + children: [ + Expanded(child: Text('Comments (${_comments.length})', style: _text(bold: true))), + Text('sorted by fee', style: _text(size: 12, color: _readGrey)), + ], + ), + if (!canComment) Text('Comments open when the story is in a block.', style: _text(size: 13)), + if (loadError != null) Text(loadError, style: _text(size: 12)), + for (final comment in _comments) _CommentRow(comment: comment), + ], + ), + ), + if (canComment) + Padding( + padding: const EdgeInsets.fromLTRB(2, 6, 2, 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 6, + children: [ + SailTextField(controller: _body, hintText: 'Comment', minLines: 3, maxLines: 3), + Row( + spacing: 6, + children: [ + SailText.primary13('Fee:'), + SizedBox( + width: 120, + child: SailTextField(controller: _fee, hintText: '', textFieldType: TextFieldType.number), + ), + SailText.primary13(activeTicker.subunit), + const Spacer(), + SailText.primary13('$_length / ${story.maxCommentChars}', bold: _length > story.maxCommentChars), + SailButton( + label: 'Comment', + loading: _posting, + disabled: _body.text.trim().isEmpty || refusal != null, + onPressed: _post, + ), + ], + ), + if (refusal != null) SailText.primary13(refusal, bold: true), + if (postError != null) SailText.primary13(postError, bold: true), + ], + ), + ), + _StatusBar( + cells: [ + 'Fee: ${formatSatoshis(story.feeSats.toInt())} or more', + '${story.maxCommentChars} characters or less', + ], + ), + ], + ); + } +} + +class _CommentRow extends StatelessWidget { + final Comment comment; + + const _CommentRow({required this.comment}); + + @override + Widget build(BuildContext context) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 150, + child: Text(formatSatoshis(comment.feeSats.toInt()), style: _text(), textAlign: TextAlign.right), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + comment.pending ? 'Pending' : _time(comment.createTime.toDateTime()), + style: _text(size: 12, color: _metaGrey), + ), + SelectableText(comment.body, style: _text()), + ], + ), + ), + ], + ); + } +} + +/// Adds the fee of a new reaction to the total of one emoji on [story]. +class ReactionDialog extends StatefulWidget { + final CoinNews story; + final String emoji; + + const ReactionDialog({super.key, required this.story, required this.emoji}); + + @override + State createState() => _ReactionDialogState(); +} + +class _ReactionDialogState extends State { + MiscAPI get _api => GetIt.I.get().misc; + + late String _emoji = widget.emoji; + final _fee = TextEditingController(); + String? _error; + + @override + void initState() { + super.initState(); + _fee.addListener(() => setState(() {})); + unawaited(_estimate()); + } + + @override + void dispose() { + _fee.dispose(); + super.dispose(); + } + + Future _estimate() async { + try { + final estimate = await _api.estimateNewsFee(NewsAction.NEWS_ACTION_REACTION, emoji: _emoji); + if (mounted && _fee.text.isEmpty) { + _fee.text = '${estimate.feeSats}'; + } + } catch (e) { + if (mounted) { + setState(() => _error = errorText(e)); + } + } + } + + int get _total => widget.story.reactions.firstWhereOrNull((r) => r.emoji == _emoji)?.feeSats.toInt() ?? 0; + + Future _send() async { + final fee = int.tryParse(_fee.text.trim()); + if (fee == null || fee <= 0) { + setState(() => _error = 'The fee must be more than zero.'); + return; + } + try { + await _api.reactNews(widget.story.itemId, _emoji, feeSats: fee); + if (mounted) { + Navigator.of(context).pop(); + } + } catch (e) { + if (mounted) { + setState(() => _error = errorText(e)); + } + } + } + + @override + Widget build(BuildContext context) { + final fee = int.tryParse(_fee.text.trim()) ?? 0; + final error = _error; + return Dialog( + backgroundColor: Colors.transparent, + child: SailCard( + title: 'Add a reaction', + width: 360, + withCloseButton: true, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 12, + children: [ + Row( + spacing: 4, + children: [ + SizedBox(width: 72, child: SailText.primary13('Reaction:')), + for (final emoji in reactionEmoji) + SailButton( + label: emoji, + variant: emoji == _emoji ? ButtonVariant.primary : ButtonVariant.secondary, + skipLoading: true, + onPressed: () async => setState(() => _emoji = emoji), + ), + ], + ), + Row( + spacing: 4, + children: [ + SizedBox(width: 72, child: SailText.primary13('Fee:')), + SizedBox( + width: 120, + child: SailTextField(controller: _fee, hintText: '', textFieldType: TextFieldType.number), + ), + SailText.primary13(activeTicker.subunit), + ], + ), + Padding( + padding: const EdgeInsets.only(left: 76), + child: Text( + '$_emoji ${formatSatoshis(_total)} → ${formatSatoshis(_total + fee)}', + style: _text(bold: true), + ), + ), + if (error != null) SailText.primary13(error, bold: true), + Row( + mainAxisAlignment: MainAxisAlignment.end, + spacing: 6, + children: [ + SailButton(label: 'Send', onPressed: _send), + SailButton( + label: 'Cancel', + variant: ButtonVariant.secondary, + skipLoading: true, + onPressed: () async => Navigator.of(context).pop(), + ), + ], + ), + ], + ), + ), + ); + } +} + +/// Opens [link] from a story. The first time, a warning shows the full address. +Future openStoryLink(BuildContext context, Uri link) async { + final settings = GetIt.I.get(); + if ((await settings.getValue(LinkWarningOffSetting())).value) { + await openUrl(link); + return; + } + if (!context.mounted) { + return; + } + final open = await showThemedDialog( + context: context, + builder: (_) => Win95(child: LinkWarningDialog(link: link)), + ); + if (open == true) { + await openUrl(link); + } +} + +/// Asks before a story link opens, and shows the full address. +class LinkWarningDialog extends StatefulWidget { + final Uri link; + + const LinkWarningDialog({super.key, required this.link}); + + @override + State createState() => _LinkWarningDialogState(); +} + +class _LinkWarningDialogState extends State { + bool _off = false; + + Future _close(bool open) async { + if (open && _off) { + await GetIt.I.get().setValue(LinkWarningOffSetting(newValue: true)); + } + if (mounted) { + Navigator.of(context).pop(open); + } + } + + @override + Widget build(BuildContext context) { + return Dialog( + backgroundColor: Colors.transparent, + child: SailCard( + title: 'Open link?', + width: 460, + withCloseButton: true, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 12, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 14, + children: [ + SailSVG.fromAsset(SailSVGAsset.triangleAlert, width: 32, color: _ink), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 6, + children: [ + SailText.primary13('You clicked a link from a random crypto user.', bold: true), + SailText.primary13('Read the address. Open it only if you trust it.'), + ], + ), + ), + ], + ), + _Sunken(child: SelectableText(widget.link.toString(), style: _text(size: 13))), + SailCheckbox( + value: _off, + label: 'Do not warn me again', + onChanged: (value) => setState(() => _off = value), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + spacing: 6, + children: [ + SailButton( + label: 'Open link', + variant: ButtonVariant.secondary, + skipLoading: true, + onPressed: () => _close(true), + ), + SailButton(label: 'Cancel', skipLoading: true, onPressed: () => _close(false)), + ], + ), + ], + ), + ), + ); + } +} + +class _Toolbar extends StatelessWidget { + final List children; + + const _Toolbar({required this.children}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(2, 2, 2, 6), + child: Row(spacing: 6, children: children), + ); + } +} + +class _BackButton extends StatelessWidget { + final VoidCallback onBack; + + const _BackButton({required this.onBack}); + + @override + Widget build(BuildContext context) { + return SailButton( + label: '< Back', + variant: ButtonVariant.secondary, + skipLoading: true, + onPressed: () async => onBack(), + ); + } +} + +/// The white page of the window, in a sunken frame. +class _Paper extends StatelessWidget { + final List children; + + const _Paper({required this.children}); + + @override + Widget build(BuildContext context) { + return _Sunken( + padding: EdgeInsets.zero, + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(20, 16, 20, 16), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 12, children: children), + ), + ); + } +} + +class _Sunken extends StatelessWidget { + final Widget child; + final EdgeInsets padding; + + const _Sunken({required this.child, this.padding = const EdgeInsets.symmetric(horizontal: 6, vertical: 4)}); + + @override + Widget build(BuildContext context) { + final bevel = SailTheme.of(context).chrome.bevel; + return DecoratedBox( + decoration: BoxDecoration(color: _paper, border: bevel?.sunken), + child: Padding(padding: padding, child: child), + ); + } +} + +class _StatusBar extends StatelessWidget { + final List cells; + + const _StatusBar({required this.cells}); + + @override + Widget build(BuildContext context) { + final bevel = SailTheme.of(context).chrome.bevel; + return Padding( + padding: const EdgeInsets.only(top: 4), + child: Row( + spacing: 2, + children: [ + for (final (i, cell) in cells.indexed) + _grow( + i == cells.length - 1, + DecoratedBox( + decoration: BoxDecoration(border: bevel?.sunken), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3), + child: SailText.primary12(cell), + ), + ), + ), + ], + ), + ); + } + + Widget _grow(bool last, Widget child) => last ? Expanded(child: child) : child; +} + +class _Link extends StatelessWidget { + final String text; + final double size; + final Future Function() onTap; + + const _Link({required this.text, required this.onTap, this.size = 14}); + + @override + Widget build(BuildContext context) { + return MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: () => unawaited(onTap()), + child: Text( + text, + style: _text(size: size, color: _linkBlue, underline: true), + ), + ), + ); + } +} diff --git a/bitwindow/lib/widgets/fee_coinnews.dart b/bitwindow/lib/widgets/fee_coinnews.dart index 3f8de88134..7ba81f3020 100644 --- a/bitwindow/lib/widgets/fee_coinnews.dart +++ b/bitwindow/lib/widgets/fee_coinnews.dart @@ -1,4 +1,5 @@ import 'package:bitwindow/env.dart'; +import 'package:bitwindow/main.dart'; import 'package:bitwindow/pages/overview_page.dart'; import 'package:bitwindow/providers/news_provider.dart'; import 'package:bitwindow/widgets/coinnews.dart'; @@ -22,6 +23,7 @@ class FeeCoinNewsView extends ViewModelWidget { title: 'Coin News', titleTooltip: "On-chain news ranked by fee, within each topic's retention window", error: viewModel.readError, + newWindow: SubWindowTypes.coinNews, widgetHeaderEnd: SailRowMenuButton(items: () => coinNewsMenuItems(context)), child: SailColumn( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/bitwindow/lib/widgets/news_cost.dart b/bitwindow/lib/widgets/news_cost.dart index f54d7247da..8dd02d17e7 100644 --- a/bitwindow/lib/widgets/news_cost.dart +++ b/bitwindow/lib/widgets/news_cost.dart @@ -5,7 +5,7 @@ import 'package:flutter/widgets.dart'; import 'package:get_it/get_it.dart'; import 'package:sail_ui/sail_ui.dart'; -/// Prices a CoinNews action and warns the user the first time they pay for one. +/// Prices a CoinNews action. class NewsCost { /// The cost of the action for this body, or why the wallet could not price it. static Future estimate(NewsAction action, {required String body}) async { @@ -15,67 +15,6 @@ class NewsCost { return (estimate: null, error: errorText(e)); } } - - /// Shows the on-chain warning, with the cost of [body], the first time the user comments. - /// Returns false only when the user backs out. - static Future confirmFirstComment(BuildContext context, {required String body}) async { - final settings = GetIt.I.get(); - if ((await settings.getValue(CommentWarningSeenSetting())).value) { - return true; - } - - final fee = await NewsCost.estimate(NewsAction.NEWS_ACTION_COMMENT, body: body); - if (!context.mounted) { - return false; - } - - final confirmed = await _showWarning(context, fee: fee); - if (!confirmed) { - return false; - } - - await settings.setValue(CommentWarningSeenSetting(newValue: true)); - return true; - } - - static Future _showWarning(BuildContext context, {required NewsFeeResult fee}) async { - var confirmed = false; - - await showThemedDialog( - context: context, - builder: (context) => SailDialog( - title: 'Commenting costs a fee', - maxWidth: 440, - withCloseButton: true, - action: SailDialogAction( - label: 'Comment', - onPressed: () async { - confirmed = true; - Navigator.of(context).pop(); - }, - ), - child: SailColumn( - spacing: SailStyleValues.padding12, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SailText.primary13( - 'Commenting writes a transaction to the chain, so it costs a network fee and lands in about ten minutes.', - overflow: TextOverflow.visible, - ), - if (fee.estimate case final estimate?) ...[ - SailText.primary20(feeAmount(estimate), bold: true), - SailText.secondary12(feeRate(estimate)), - ], - if (fee.error case final error?) SailText.secondary12(error, color: context.sailTheme.colors.error), - SailText.secondary12('You only see this once.'), - ], - ), - ), - ); - - return confirmed; - } } /// The fee of a news action, or why the wallet could not price it. diff --git a/bitwindow/pubspec.lock b/bitwindow/pubspec.lock index 8219096ec1..6e11eadc8d 100644 --- a/bitwindow/pubspec.lock +++ b/bitwindow/pubspec.lock @@ -452,7 +452,7 @@ packages: source: sdk version: "0.0.0" flutter_markdown: - dependency: "direct main" + dependency: transitive description: path: "../third_party/flutter_markdown" relative: true diff --git a/bitwindow/pubspec.yaml b/bitwindow/pubspec.yaml index 78964ec103..599a62fc91 100644 --- a/bitwindow/pubspec.yaml +++ b/bitwindow/pubspec.yaml @@ -3,7 +3,7 @@ description: "A frontend for interacting with a Drivechain-enabled layer 1 bitcoin network." publish_to: "none" -version: 0.2.296 +version: 0.2.297 environment: sdk: 3.13.7 @@ -48,8 +48,6 @@ dependencies: protobuf: ^6.1.0 # 0.6 lets a raw WM_CLOSE past setPreventClose on Windows. window_manager: ^0.5.2 - flutter_markdown: - path: ../third_party/flutter_markdown path: ^1.9.1 pointycastle: path: ../third_party/pointycastle diff --git a/bitwindow/server/api/misc/misc.go b/bitwindow/server/api/misc/misc.go index 1fbd1e4d18..2358495aae 100644 --- a/bitwindow/server/api/misc/misc.go +++ b/bitwindow/server/api/misc/misc.go @@ -235,6 +235,9 @@ func newsPayloadFor(req *miscv1.EstimateNewsFeeRequest) ([]byte, error) { case miscv1.NewsAction_NEWS_ACTION_TOPIC: return topicPayload(opreturns.TopicID{}, req.TopicName, req.RetentionDays) + case miscv1.NewsAction_NEWS_ACTION_REACTION: + return codec.EncodeReaction(codec.Reaction{Emoji: req.Emoji}) + case miscv1.NewsAction_NEWS_ACTION_UNSPECIFIED: return nil, errors.New("action must be set") @@ -406,12 +409,32 @@ func (s *Server) ListCoinNews(ctx context.Context, req *miscv1.ListCoinNewsReque ) }) local := lo.GroupBy(indexed, func(n opreturns.CoinNews) opreturns.TopicID { return n.Topic }) + rules, err := cnstore.StoryRulesOf(ctx, s.database) + if err != nil { + return nil, err + } + reactions, err := cnstore.ListReactions(ctx, s.database) + if err != nil { + return nil, err + } + toProto := func(n opreturns.CoinNews) *miscv1.CoinNews { + story := coinNewsToProto(n, 0) + rule, found := rules[n.ItemID] + if !found { + rule = codec.StoryRules{Headline: n.Headline, Body: n.Content} + } + story.MaxCommentChars = int32(rule.MaxCommentLen()) + story.Reactions = lo.Map(reactions[n.ItemID], func(r cnstore.Reaction, _ int) *miscv1.Reaction { + return &miscv1.Reaction{Emoji: r.Emoji, FeeSats: r.FeeSats} + }) + return story + } var out []rankedStory var indexerErr error for _, topic := range topics { news := lo.Map(local[topic], func(n opreturns.CoinNews, i int) rankedStory { - return rankedStory{story: coinNewsToProto(n, i), height: n.BlockHeight} + return rankedStory{story: toProto(n), height: n.BlockHeight} }) var items []engines.RemoteItem items, indexerErr = s.indexerItems(ctx, topic, retention[topic], indexerErr) @@ -421,7 +444,7 @@ func (s *Server) ListCoinNews(ctx context.Context, req *miscv1.ListCoinNewsReque }) for _, story := range pending { if story.Topic == topic && !confirmed[fmt.Sprintf("%s:%d", story.TxID, story.Vout)] { - news = append(news, rankedStory{story: coinNewsToProto(story, 0)}) + news = append(news, rankedStory{story: toProto(story)}) } } rankCoinNews(news) @@ -457,10 +480,27 @@ func mergeStories(local, remote []rankedStory) []rankedStory { if l.story.FeeSats == 0 { l.story.FeeSats = r.story.FeeSats } + l.story.Reactions = mergeReactions(l.story.Reactions, r.story.Reactions) } return local } +// mergeReactions keeps the higher total of each emoji: one source can lag the other. +func mergeReactions(local, remote []*miscv1.Reaction) []*miscv1.Reaction { + totals := map[string]int64{} + for _, r := range slices.Concat(local, remote) { + totals[r.Emoji] = max(totals[r.Emoji], r.FeeSats) + } + out := make([]*miscv1.Reaction, 0, len(totals)) + for emoji, fee := range totals { + out = append(out, &miscv1.Reaction{Emoji: emoji, FeeSats: fee}) + } + slices.SortFunc(out, func(a, b *miscv1.Reaction) int { + return cmp.Or(cmp.Compare(b.FeeSats, a.FeeSats), strings.Compare(a.Emoji, b.Emoji)) + }) + return out +} + // remoteCoinNewsPages is the number of indexer pages that one topic can take. const remoteCoinNewsPages = 10 @@ -543,6 +583,10 @@ func rankCoinNews(news []rankedStory) { func remoteCoinNewsToProto(item engines.RemoteItem, _ int) *miscv1.CoinNews { return &miscv1.CoinNews{ + MaxCommentChars: int32(codec.StoryRules{Headline: item.Headline, Body: item.Body}.MaxCommentLen()), + Reactions: lo.Map(item.Reactions, func(r engines.RemoteReaction, _ int) *miscv1.Reaction { + return &miscv1.Reaction{Emoji: r.Emoji, FeeSats: r.FeeSats} + }), Topic: item.TopicHex, Headline: codec.Line(item.Headline), Content: codec.Text(item.Body), @@ -590,6 +634,16 @@ func (s *Server) CommentNews(ctx context.Context, req *miscv1.CommentNewsRequest err := errors.New("comment must have a body or url") return nil, connect.NewError(connect.CodeInvalidArgument, err.Error()).WithCause(err) } + if req.FeeSats == 0 { + return nil, connect.NewError(connect.CodeInvalidArgument, "fee_sats must be set") + } + story, err := s.rootStory(ctx, parent) + if err != nil { + return nil, err + } + if err := codec.CheckComment(story, int64(req.FeeSats), strings.TrimSpace(req.Body)); err != nil { + return nil, connect.NewError(connect.CodeInvalidArgument, err.Error()).WithCause(err) + } priv, xpk, err := cnstore.LoadOrCreateIdentity(ctx, s.database) if err != nil { @@ -614,7 +668,7 @@ func (s *Server) CommentNews(ctx context.Context, req *miscv1.CommentNewsRequest return nil, fmt.Errorf("comment news: encode comment: %w", err) } - txid, err := s.walletEngine.BroadcastOpReturn(ctx, commentBytes, req.FeeSatPerVbyte, req.FeeSats) + txid, err := s.walletEngine.BroadcastOpReturn(ctx, commentBytes, 0, req.FeeSats) if err != nil { return nil, fmt.Errorf("comment news: %w", err) } @@ -629,6 +683,47 @@ func (s *Server) CommentNews(ctx context.Context, req *miscv1.CommentNewsRequest }, nil } +// rootStory finds the story at the top of the parent chain, in the local index +// or else at the indexer. +func (s *Server) rootStory(ctx context.Context, parent codec.ItemID) (codec.StoryRules, error) { + story, found, err := cnstore.RootStory(ctx, s.database, parent) + if err != nil { + return codec.StoryRules{}, err + } + if found { + return story, nil + } + item, found, err := s.remoteCoinNews.GetItem(ctx, parent.String()) + if err != nil && !errors.Is(err, engines.ErrNoIndexer) { + return codec.StoryRules{}, fmt.Errorf("read the story at the indexer: %w", err) + } + if !found { + return codec.StoryRules{}, connect.NewError(connect.CodeFailedPrecondition, "the story is not in a block yet") + } + return codec.StoryRules{FeeSats: item.FeeSats, Headline: item.Headline, Body: item.Body}, nil +} + +// ReactNews implements miscv1connect.MiscServiceHandler. +func (s *Server) ReactNews(ctx context.Context, req *miscv1.ReactNewsRequest) (*miscv1.ReactNewsResponse, error) { + parent, err := parseItemID(req.ParentId, "parent_id") + if err != nil { + return nil, err + } + if req.FeeSats == 0 { + return nil, connect.NewError(connect.CodeInvalidArgument, "fee_sats must be set") + } + payload, err := codec.EncodeReaction(codec.Reaction{Parent: parent, Emoji: req.Emoji}) + if err != nil { + return nil, connect.NewError(connect.CodeInvalidArgument, err.Error()).WithCause(err) + } + txid, err := s.walletEngine.BroadcastOpReturn(ctx, payload, 0, req.FeeSats) + if err != nil { + return nil, fmt.Errorf("react news: %w", err) + } + zerolog.Ctx(ctx).Info().Str("parent_id", req.ParentId).Str("txid", txid).Msg("broadcast reaction transaction") + return &miscv1.ReactNewsResponse{Txid: txid}, nil +} + // commentTLVs builds the trailing TLV section for a comment from the // request's optional fields, in a stable order (the signature covers // these exact bytes). diff --git a/bitwindow/server/api/misc/misc_test.go b/bitwindow/server/api/misc/misc_test.go index 1b939d07ca..25964e2577 100644 --- a/bitwindow/server/api/misc/misc_test.go +++ b/bitwindow/server/api/misc/misc_test.go @@ -461,6 +461,28 @@ func TestService_Comments(t *testing.T) { return mockOrch } + // storyInBlock indexes a story with this fee and returns its ItemID. + storyInBlock := func(t *testing.T, db *sql.DB, headline string, fee int64) string { + t.Helper() + topic, err := opreturns.ValidNewsTopicID("a1a1a1a1") + require.NoError(t, err) + payload, err := opreturns.EncodeNewsMessageWithOptions(topic, headline, "", opreturns.StoryOptions{}) + require.NoError(t, err) + txid := strings.Repeat("e5", 32) + height := uint32(100) + require.NoError(t, opreturns.Persist(t.Context(), db, []opreturns.OPReturn{ + {TxID: txid, Data: payload, Fee: btcutil.Amount(fee), Height: &height}, + })) + tag, msg, err := coinnews.DecodeMessage(payload) + require.NoError(t, err) + require.NoError(t, cnstore.Index(t.Context(), db, cnstore.IndexEnv{ + Pos: cnstore.BlockPos{BlockHeight: height, BlockTime: time.Now(), TxID: txid}, TypeTag: tag, Msg: msg, + })) + id, err := cnstore.ItemIDOf(txid, 0) + require.NoError(t, err) + return id.String() + } + t.Run("comment rejects a short parent_id", func(t *testing.T) { t.Parallel() cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, database.Test(t))) @@ -479,10 +501,13 @@ func TestService_Comments(t *testing.T) { t.Run("comment success", func(t *testing.T) { t.Parallel() - cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, database.Test(t), apitests.WithOrchestrator(walletReturningTxid(t)))) + db := database.Test(t) + story := storyInBlock(t, db, "A story about a great article", 1000) + cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, db, apitests.WithOrchestrator(walletReturningTxid(t)))) resp, err := cli.CommentNews(t.Context(), &miscv1.CommentNewsRequest{ - ParentId: validItemID, + ParentId: story, Body: "great article", + FeeSats: 1000, }) require.NoError(t, err) assert.NotEmpty(t, resp.Txid) @@ -499,6 +524,38 @@ func TestService_Comments(t *testing.T) { }) // walletPreviewing prices a preview at 21 sat/vB, and records each payload. + t.Run("comment obeys the rules of the story", func(t *testing.T) { + t.Parallel() + db := database.Test(t) + story := storyInBlock(t, db, "Ten chars!", 1000) + cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, db, apitests.WithOrchestrator(walletReturningTxid(t)))) + + for _, tc := range []struct { + name, body, wantErr string + fee uint64 + }{ + {"no fee", "ok", "fee_sats must be set", 0}, + {"fee below the story fee", "ok", "lower than the story fee", 999}, + {"longer than the story", "eleven char", "longer than the story", 1000}, + {"equal fee and length", "ten chars!", "", 1000}, + } { + _, err := cli.CommentNews(t.Context(), &miscv1.CommentNewsRequest{ParentId: story, Body: tc.body, FeeSats: tc.fee}) + if tc.wantErr == "" { + require.NoError(t, err, tc.name) + continue + } + require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err), tc.name) + assert.Contains(t, err.Error(), tc.wantErr, tc.name) + } + }) + + t.Run("comment on a story that no index holds", func(t *testing.T) { + t.Parallel() + cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, database.Test(t))) + _, err := cli.CommentNews(t.Context(), &miscv1.CommentNewsRequest{ParentId: validItemID, Body: "hi", FeeSats: 1000}) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err)) + }) + walletPreviewing := func(t *testing.T, previewed, sent *[]string) *mocks.MockWalletManagerServiceClient { t.Helper() mockOrch := mocks.NewMockWalletManagerServiceClient(gomock.NewController(t)) @@ -521,6 +578,34 @@ func TestService_Comments(t *testing.T) { return mockOrch } + t.Run("react news broadcasts the reaction", func(t *testing.T) { + t.Parallel() + var previewed, sent []string + cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, database.Test(t), apitests.WithOrchestrator(walletPreviewing(t, &previewed, &sent)))) + + _, err := cli.ReactNews(t.Context(), &miscv1.ReactNewsRequest{ParentId: validItemID, Emoji: "👎", FeeSats: 8000}) + require.NoError(t, err) + require.Len(t, sent, 1) + raw, err := hex.DecodeString(sent[0]) + require.NoError(t, err) + _, msg, err := coinnews.DecodeMessage(raw) + require.NoError(t, err) + assert.Equal(t, &coinnews.Reaction{Parent: lo.Must(coinnews.ParseItemID(validItemID)), Emoji: "👎"}, msg) + + estimate, err := cli.EstimateNewsFee(t.Context(), &miscv1.EstimateNewsFeeRequest{ + Action: miscv1.NewsAction_NEWS_ACTION_REACTION, Emoji: "👎", + }) + require.NoError(t, err) + require.Len(t, previewed, 1) + assert.Len(t, previewed[0], len(sent[0]), "the estimate prices a payload of the size that the reaction sends") + assert.Positive(t, estimate.FeeSats) + + _, err = cli.ReactNews(t.Context(), &miscv1.ReactNewsRequest{ParentId: validItemID, Emoji: "", FeeSats: 8000}) + require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err)) + _, err = cli.ReactNews(t.Context(), &miscv1.ReactNewsRequest{ParentId: validItemID, Emoji: "👍"}) + require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err)) + }) + t.Run("comment fee estimate counts the url", func(t *testing.T) { t.Parallel() var previewed, sent []string @@ -551,14 +636,16 @@ func TestService_Comments(t *testing.T) { t.Run("comment fee estimate is the wallet preview of the comment bytes", func(t *testing.T) { t.Parallel() var previewed, sent []string - cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, database.Test(t), apitests.WithOrchestrator(walletPreviewing(t, &previewed, &sent)))) + db := database.Test(t) + story := storyInBlock(t, db, "A story about a great article", 1000) + cli := miscv1connect.NewMiscServiceClient(apitests.RPC(t, db, apitests.WithOrchestrator(walletPreviewing(t, &previewed, &sent)))) estimate, err := cli.EstimateNewsFee(t.Context(), &miscv1.EstimateNewsFeeRequest{ Action: miscv1.NewsAction_NEWS_ACTION_COMMENT, Body: "great article æøå", }) require.NoError(t, err) - _, err = cli.CommentNews(t.Context(), &miscv1.CommentNewsRequest{ParentId: validItemID, Body: "great article æøå"}) + _, err = cli.CommentNews(t.Context(), &miscv1.CommentNewsRequest{ParentId: story, Body: "great article æøå", FeeSats: 1000}) require.NoError(t, err) require.Len(t, previewed, 1) diff --git a/bitwindow/server/api/misc/remote_test.go b/bitwindow/server/api/misc/remote_test.go index 356faa122c..0d38648da6 100644 --- a/bitwindow/server/api/misc/remote_test.go +++ b/bitwindow/server/api/misc/remote_test.go @@ -31,6 +31,11 @@ func (stubRemote) ListThread(context.Context, string) ([]engines.RemoteComment, return nil, nil } +func (s stubRemote) GetItem(_ context.Context, itemIDHex string) (engines.RemoteItem, bool, error) { + item, found := lo.Find(s, func(item engines.RemoteItem) bool { return item.ItemIDHex == itemIDHex }) + return item, found, nil +} + type noIndexer struct{} func (noIndexer) ListThread(context.Context, string) ([]engines.RemoteComment, error) { @@ -41,6 +46,10 @@ func (noIndexer) ListFrontPage(context.Context, string, uint32, uint32) ([]engin return nil, engines.ErrNoIndexer } +func (noIndexer) GetItem(context.Context, string) (engines.RemoteItem, bool, error) { + return engines.RemoteItem{}, false, engines.ErrNoIndexer +} + func TestService_ListCoinNews_RemoteFee(t *testing.T) { t.Parallel() remote := stubRemote{ @@ -179,6 +188,10 @@ func (failedIndexer) ListThread(context.Context, string) ([]engines.RemoteCommen return nil, errors.New("connection refused") } +func (failedIndexer) GetItem(context.Context, string) (engines.RemoteItem, bool, error) { + return engines.RemoteItem{}, false, errors.New("connection refused") +} + type remoteThread struct { noIndexer comments []engines.RemoteComment @@ -365,3 +378,22 @@ func TestService_CoinNews_IndexerStopsAfterARead(t *testing.T) { require.Len(t, comments.Comments, 1) assert.Equal(t, "First", comments.Comments[0].Body) } + +func TestService_ListCoinNews_ReactionsAndCommentLimit(t *testing.T) { + t.Parallel() + remote := stubRemote{{ + ItemIDHex: "aa", TopicHex: "a1a1a1a1", Headline: "Héllo", Body: "wörld", FeeSats: 5000, BlockTime: time.Now(), + Reactions: []engines.RemoteReaction{{Emoji: "👎", FeeSats: 8617}, {Emoji: "👍", FeeSats: 3513}}, + }} + srv := misc.New(database.Test(t), nil, nil, nil, remote) + + resp, err := srv.ListCoinNews(t.Context(), &miscv1.ListCoinNewsRequest{}) + require.NoError(t, err) + require.Len(t, resp.CoinNews, 1) + story := resp.CoinNews[0] + assert.EqualValues(t, 10, story.MaxCommentChars) + require.Len(t, story.Reactions, 2) + assert.Equal(t, "👎", story.Reactions[0].Emoji) + assert.EqualValues(t, 8617, story.Reactions[0].FeeSats) + assert.Equal(t, "👍", story.Reactions[1].Emoji) +} diff --git a/bitwindow/server/database/migrations/063_cn_reactions.sql b/bitwindow/server/database/migrations/063_cn_reactions.sql new file mode 100644 index 0000000000..d20586757a --- /dev/null +++ b/bitwindow/server/database/migrations/063_cn_reactions.sql @@ -0,0 +1,7 @@ +-- CoinNews reactions (spec §8). A total is the sum of the fees of one emoji on one item. +CREATE TABLE cn_reactions ( + item_id BLOB(12) PRIMARY KEY REFERENCES cn_items(item_id), + parent_id BLOB(12) NOT NULL, + emoji TEXT NOT NULL +); +CREATE INDEX idx_cn_reactions_parent ON cn_reactions (parent_id); diff --git a/bitwindow/server/engines/coinnews.go b/bitwindow/server/engines/coinnews.go index 2cc8fee76b..776799eac4 100644 --- a/bitwindow/server/engines/coinnews.go +++ b/bitwindow/server/engines/coinnews.go @@ -105,6 +105,35 @@ func indexCoinNewsPayload(ctx context.Context, db *sql.DB, data []byte, pos cnst dropMsg(ctx, pos, "comment parent unresolvable", nil) return nil } + story, ok, err := cnstore.RootStory(ctx, db, m.Parent) + if err != nil { + return err + } + if !ok { + dropMsg(ctx, pos, "comment has no root story", nil) + return nil + } + fee, err := cnstore.TxFee(ctx, db, pos.TxID) + if err != nil { + return err + } + var body string + if t := codec.FindFirst(m.TLVs, codec.TLVBody); t != nil { + body = string(t.Value) + } + if err := codec.CheckComment(story, fee, body); err != nil { + dropMsg(ctx, pos, "comment breaks the story rules", err) + return nil + } + case *codec.Reaction: + parent, ok, err := cnstore.ResolveItem(ctx, db, m.Parent) + if err != nil { + return err + } + if !ok || !parent.Before(self) { + dropMsg(ctx, pos, "reaction parent unresolvable", nil) + return nil + } case *codec.Continuation: // §9: continuations live in the head's tx or a later tx in the // same block, after the head in scan order. @@ -112,7 +141,7 @@ func indexCoinNewsPayload(ctx context.Context, db *sql.DB, data []byte, pos cnst if err != nil { return err } - if !ok || head.BlockHeight != pos.BlockHeight || !head.Before(self) { + if !ok || head.TypeTag != codec.TypeStory || head.BlockHeight != pos.BlockHeight || !head.Before(self) { dropMsg(ctx, pos, "continuation head unresolvable", nil) return nil } @@ -267,6 +296,7 @@ func purgeCoinNewsAtOrAboveTx(ctx context.Context, tx *sql.Tx, fromHeight uint32 stmts := []string{ `DELETE FROM cn_stories WHERE item_id IN (SELECT item_id FROM cn_items WHERE block_height >= ?)`, `DELETE FROM cn_comments WHERE item_id IN (SELECT item_id FROM cn_items WHERE block_height >= ?)`, + `DELETE FROM cn_reactions WHERE item_id IN (SELECT item_id FROM cn_items WHERE block_height >= ?)`, `DELETE FROM cn_continuations WHERE block_height >= ?`, // An empty txid marks a local bootstrap row, not a creation on chain. // No block replays it, so a delete here loses it for good. diff --git a/bitwindow/server/engines/coinnews_remote.go b/bitwindow/server/engines/coinnews_remote.go index b0f08211e7..f5c5abb5e9 100644 --- a/bitwindow/server/engines/coinnews_remote.go +++ b/bitwindow/server/engines/coinnews_remote.go @@ -30,6 +30,9 @@ type RemoteCoinNews interface { // ListThread returns each comment under the root item. It returns // ErrNoIndexer when the network publishes none. ListThread(ctx context.Context, rootIDHex string) ([]RemoteComment, error) + // GetItem returns one story, false when the indexer has none. It returns + // ErrNoIndexer when the network publishes none. + GetItem(ctx context.Context, itemIDHex string) (RemoteItem, bool, error) } // RemoteItem is one indexed CoinNews story as the indexer renders it. @@ -46,6 +49,14 @@ type RemoteItem struct { FeeSats int64 TxID string Vout uint32 + // Reactions to the story, highest total first. + Reactions []RemoteReaction +} + +// RemoteReaction is the fee total of one emoji on an item. +type RemoteReaction struct { + Emoji string + FeeSats int64 } // RemoteComment is one indexed CoinNews comment as the indexer renders it. @@ -157,24 +168,48 @@ func (r *connectRemote) ListFrontPage(ctx context.Context, topicHex string, limi out := make([]RemoteItem, len(res.Items)) for i, item := range res.Items { - out[i] = RemoteItem{ - ItemIDHex: item.ItemIdHex, - TopicHex: item.TopicHex, - Headline: item.Headline, - URL: item.Url, - Body: item.Body, - Subtype: int32(item.Subtype), - NSFW: item.Nsfw, - BlockHeight: item.BlockHeight, - BlockTime: item.BlockTime.AsTime(), - FeeSats: item.FeeSats, - TxID: item.Txid, - Vout: item.Vout, - } + out[i] = remoteItem(item) } return out, nil } +func (r *connectRemote) GetItem(ctx context.Context, itemIDHex string) (RemoteItem, bool, error) { + client := r.resolve(ctx) + if client == nil { + return RemoteItem{}, false, ErrNoIndexer + } + res, err := client.GetItem(ctx, &coinnewsv1.GetItemRequest{ItemIdHex: itemIDHex}) + if connect.CodeOf(err) == connect.CodeNotFound { + return RemoteItem{}, false, nil + } + if err != nil { + return RemoteItem{}, false, err + } + return remoteItem(res.Item), true, nil +} + +func remoteItem(item *coinnewsv1.Item) RemoteItem { + reactions := make([]RemoteReaction, len(item.Reactions)) + for i, r := range item.Reactions { + reactions[i] = RemoteReaction{Emoji: r.Emoji, FeeSats: r.FeeSats} + } + return RemoteItem{ + ItemIDHex: item.ItemIdHex, + TopicHex: item.TopicHex, + Headline: item.Headline, + URL: item.Url, + Body: item.Body, + Subtype: int32(item.Subtype), + NSFW: item.Nsfw, + BlockHeight: item.BlockHeight, + BlockTime: item.BlockTime.AsTime(), + FeeSats: item.FeeSats, + TxID: item.Txid, + Vout: item.Vout, + Reactions: reactions, + } +} + func (r *connectRemote) ListThread(ctx context.Context, rootIDHex string) ([]RemoteComment, error) { client := r.resolve(ctx) if client == nil { diff --git a/bitwindow/server/engines/coinnews_rules_test.go b/bitwindow/server/engines/coinnews_rules_test.go new file mode 100644 index 0000000000..d1cb80190b --- /dev/null +++ b/bitwindow/server/engines/coinnews_rules_test.go @@ -0,0 +1,103 @@ +package engines + +import ( + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cnstore "github.com/LayerTwo-Labs/sidesail/bitwindow/server/models/coinnews" + "github.com/LayerTwo-Labs/sidesail/bitwindow/server/models/opreturns" + codec "github.com/LayerTwo-Labs/sidesail/coinnews/codec" +) + +// chainOf indexes each payload in its own block from height from, at the fee given, and returns the ItemIDs. +func chainOf(t *testing.T, p *Parser, from uint32, payloads [][]byte, fees []int64) []codec.ItemID { + t.Helper() + var blocks []lo.Tuple2[uint32, *wire.MsgBlock] + var rows []opreturns.OPReturn + ids := make([]codec.ItemID, len(payloads)) + for i, payload := range payloads { + block := blockOfWithPrevHash(t, [][]byte{payload}, time.Unix(1_700_000_000+int64(i), 0).UTC(), chainhash.Hash{0xce, byte(from), byte(i)}) + height := from + uint32(i) + tx := block.Transactions[0] + rows = append(rows, opreturns.OPReturn{TxID: tx.TxID(), Vout: 0, Data: payload, Fee: btcutil.Amount(fees[i]), Height: &height}) + hash := tx.TxHash() + ids[i] = codec.ComputeItemID([32]byte(hash), 0) + blocks = append(blocks, lo.T2(height, block)) + } + require.NoError(t, opreturns.Persist(t.Context(), p.db, rows)) + require.NoError(t, p.indexCoinNewsBlocks(t.Context(), blocks)) + return ids +} + +func signedCommentOn(t *testing.T, key *btcec.PrivateKey, parent codec.ItemID, body string) []byte { + t.Helper() + tlvs := []codec.TLV{{Tag: codec.TLVBody, Value: []byte(body)}} + blob, err := codec.SerialiseTLVs(tlvs) + require.NoError(t, err) + digest := codec.CommentSigHash(parent, blob) + sig, err := schnorr.Sign(key, digest[:]) + require.NoError(t, err) + c := codec.Comment{Parent: parent, TLVs: tlvs} + copy(c.AuthorXPK[:], schnorr.SerializePubKey(key.PubKey())) + copy(c.Sig[:], sig.Serialize()) + payload, err := codec.EncodeComment(c) + require.NoError(t, err) + return payload +} + +func TestCoinNewsIndexer_CommentRules(t *testing.T) { + t.Parallel() + p := newCoinNewsParser(t) + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + + story, err := codec.EncodeStory(codec.Story{Topic: codec.Topic{1, 2, 3, 4}, Headline: "ab", TLVs: []codec.TLV{ + {Tag: codec.TLVBody, Value: []byte("cd")}, + }}) + require.NoError(t, err) + storyID := chainOf(t, p, 500, [][]byte{story}, []int64{1000})[0] + + chainOf(t, p, 501, [][]byte{ + signedCommentOn(t, key, storyID, "cheap"), + signedCommentOn(t, key, storyID, "wxyz"), + signedCommentOn(t, key, storyID, "vwxyz"), + }, []int64{999, 1000, 5000}) + + thread, err := cnstore.ListThread(t.Context(), p.db, storyID) + require.NoError(t, err) + assert.Equal(t, []string{"wxyz"}, lo.Map(thread, func(c cnstore.Comment, _ int) string { return c.Body })) +} + +func TestCoinNewsIndexer_Reactions(t *testing.T) { + t.Parallel() + p := newCoinNewsParser(t) + + story, err := codec.EncodeStory(codec.Story{Topic: codec.Topic{1, 2, 3, 4}, Headline: "Story"}) + require.NoError(t, err) + storyID := chainOf(t, p, 500, [][]byte{story}, []int64{1000})[0] + + react := func(parent codec.ItemID, emoji string) []byte { + payload, err := codec.EncodeReaction(codec.Reaction{Parent: parent, Emoji: emoji}) + require.NoError(t, err) + return payload + } + chainOf(t, p, 501, [][]byte{ + react(storyID, "👍"), react(storyID, "👎"), react(storyID, "👎"), react(codec.ItemID{0xff}, "👍"), + }, []int64{3513, 617, 8000, 9999}) + + reactions, err := cnstore.ListReactions(t.Context(), p.db) + require.NoError(t, err) + assert.Equal(t, map[string][]cnstore.Reaction{storyID.String(): { + {ParentID: storyID.String(), Emoji: "👎", FeeSats: 8617}, + {ParentID: storyID.String(), Emoji: "👍", FeeSats: 3513}, + }}, reactions) +} diff --git a/bitwindow/server/engines/coinnews_test.go b/bitwindow/server/engines/coinnews_test.go index 1a9b101009..1c7a965ac8 100644 --- a/bitwindow/server/engines/coinnews_test.go +++ b/bitwindow/server/engines/coinnews_test.go @@ -407,7 +407,7 @@ func TestPurgeAtOrAbove_NamesTheFailedStatement(t *testing.T) { }{ {"coinnews", "cn_continuations", func(ctx context.Context, tx *sql.Tx) error { return purgeCoinNewsAtOrAboveTx(ctx, tx, 100) - }, "purge coinnews statement 2"}, + }, "purge coinnews statement 3"}, {"m4", "m4_votes", func(ctx context.Context, tx *sql.Tx) error { _, err := purgeM4AtOrAboveTx(ctx, tx, 100) return err diff --git a/bitwindow/server/engines/m4_engine_replay_test.go b/bitwindow/server/engines/m4_engine_replay_test.go index 9ce0534e19..561ed847b7 100644 --- a/bitwindow/server/engines/m4_engine_replay_test.go +++ b/bitwindow/server/engines/m4_engine_replay_test.go @@ -666,6 +666,7 @@ func TestM4UpgradeRestoresTheLastBundleVote(t *testing.T) { ALTER TABLE m3_messages DROP COLUMN vote_height; ALTER TABLE op_returns DROP COLUMN explorer_message; DROP TABLE cn_subscriptions; + DROP TABLE cn_reactions; DROP TABLE consolidation_runs; DROP TABLE consolidation_coins; UPDATE withdrawal_bundles diff --git a/bitwindow/server/gen/misc/v1/misc.pb.go b/bitwindow/server/gen/misc/v1/misc.pb.go index c1b4fc35aa..bc66acab9e 100644 --- a/bitwindow/server/gen/misc/v1/misc.pb.go +++ b/bitwindow/server/gen/misc/v1/misc.pb.go @@ -89,6 +89,7 @@ const ( NewsAction_NEWS_ACTION_COMMENT NewsAction = 2 NewsAction_NEWS_ACTION_STORY NewsAction = 3 NewsAction_NEWS_ACTION_TOPIC NewsAction = 4 + NewsAction_NEWS_ACTION_REACTION NewsAction = 5 ) // Enum value maps for NewsAction. @@ -98,12 +99,14 @@ var ( 2: "NEWS_ACTION_COMMENT", 3: "NEWS_ACTION_STORY", 4: "NEWS_ACTION_TOPIC", + 5: "NEWS_ACTION_REACTION", } NewsAction_value = map[string]int32{ "NEWS_ACTION_UNSPECIFIED": 0, "NEWS_ACTION_COMMENT": 2, "NEWS_ACTION_STORY": 3, "NEWS_ACTION_TOPIC": 4, + "NEWS_ACTION_REACTION": 5, } ) @@ -823,6 +826,8 @@ type EstimateNewsFeeRequest struct { // Topic fields that change the size of the payload. TopicName string `protobuf:"bytes,8,opt,name=topic_name,json=topicName,proto3" json:"topic_name,omitempty"` RetentionDays int32 `protobuf:"varint,9,opt,name=retention_days,json=retentionDays,proto3" json:"retention_days,omitempty"` + // Reaction field that changes the size of the payload. + Emoji string `protobuf:"bytes,10,opt,name=emoji,proto3" json:"emoji,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -920,6 +925,13 @@ func (x *EstimateNewsFeeRequest) GetRetentionDays() int32 { return 0 } +func (x *EstimateNewsFeeRequest) GetEmoji() string { + if x != nil { + return x.Emoji + } + return "" +} + type EstimateNewsFeeResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Vsize uint64 `protobuf:"varint,1,opt,name=vsize,proto3" json:"vsize,omitempty"` @@ -1048,9 +1060,13 @@ type CoinNews struct { Outdated bool `protobuf:"varint,16,opt,name=outdated,proto3" json:"outdated,omitempty"` // True for a story in the mempool. Its create_time is the time that the // node first saw it, and it has no item_id. - Pending bool `protobuf:"varint,17,opt,name=pending,proto3" json:"pending,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Pending bool `protobuf:"varint,17,opt,name=pending,proto3" json:"pending,omitempty"` + // Reactions to the story, highest total first. + Reactions []*Reaction `protobuf:"bytes,18,rep,name=reactions,proto3" json:"reactions,omitempty"` + // The most characters a comment on this story can hold (spec §7.1). + MaxCommentChars int32 `protobuf:"varint,19,opt,name=max_comment_chars,json=maxCommentChars,proto3" json:"max_comment_chars,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CoinNews) Reset() { @@ -1181,6 +1197,74 @@ func (x *CoinNews) GetPending() bool { return false } +func (x *CoinNews) GetReactions() []*Reaction { + if x != nil { + return x.Reactions + } + return nil +} + +func (x *CoinNews) GetMaxCommentChars() int32 { + if x != nil { + return x.MaxCommentChars + } + return 0 +} + +// The fee total of one emoji on an item. +type Reaction struct { + state protoimpl.MessageState `protogen:"open.v1"` + Emoji string `protobuf:"bytes,1,opt,name=emoji,proto3" json:"emoji,omitempty"` + // Sum of the fees of every reaction with this emoji. + FeeSats int64 `protobuf:"varint,2,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Reaction) Reset() { + *x = Reaction{} + mi := &file_misc_v1_misc_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Reaction) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Reaction) ProtoMessage() {} + +func (x *Reaction) ProtoReflect() protoreflect.Message { + mi := &file_misc_v1_misc_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Reaction.ProtoReflect.Descriptor instead. +func (*Reaction) Descriptor() ([]byte, []int) { + return file_misc_v1_misc_proto_rawDescGZIP(), []int{14} +} + +func (x *Reaction) GetEmoji() string { + if x != nil { + return x.Emoji + } + return "" +} + +func (x *Reaction) GetFeeSats() int64 { + if x != nil { + return x.FeeSats + } + return 0 +} + type ListCoinNewsResponse struct { state protoimpl.MessageState `protogen:"open.v1"` CoinNews []*CoinNews `protobuf:"bytes,1,rep,name=coin_news,json=coinNews,proto3" json:"coin_news,omitempty"` @@ -1192,7 +1276,7 @@ type ListCoinNewsResponse struct { func (x *ListCoinNewsResponse) Reset() { *x = ListCoinNewsResponse{} - mi := &file_misc_v1_misc_proto_msgTypes[14] + mi := &file_misc_v1_misc_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1204,7 +1288,7 @@ func (x *ListCoinNewsResponse) String() string { func (*ListCoinNewsResponse) ProtoMessage() {} func (x *ListCoinNewsResponse) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[14] + mi := &file_misc_v1_misc_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1217,7 +1301,7 @@ func (x *ListCoinNewsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListCoinNewsResponse.ProtoReflect.Descriptor instead. func (*ListCoinNewsResponse) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{14} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{15} } func (x *ListCoinNewsResponse) GetCoinNews() []*CoinNews { @@ -1243,16 +1327,15 @@ type CommentNewsRequest struct { Url string `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"` Lang string `protobuf:"bytes,4,opt,name=lang,proto3" json:"lang,omitempty"` ReplyQuote string `protobuf:"bytes,5,opt,name=reply_quote,json=replyQuote,proto3" json:"reply_quote,omitempty"` - // Fee options - exactly one should be set (0 = use Core's estimate) - FeeSatPerVbyte uint64 `protobuf:"varint,6,opt,name=fee_sat_per_vbyte,json=feeSatPerVbyte,proto3" json:"fee_sat_per_vbyte,omitempty"` - FeeSats uint64 `protobuf:"varint,7,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Fee of the comment. It must be at least the fee of the root story (spec §7.1). + FeeSats uint64 `protobuf:"varint,7,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CommentNewsRequest) Reset() { *x = CommentNewsRequest{} - mi := &file_misc_v1_misc_proto_msgTypes[15] + mi := &file_misc_v1_misc_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1264,7 +1347,7 @@ func (x *CommentNewsRequest) String() string { func (*CommentNewsRequest) ProtoMessage() {} func (x *CommentNewsRequest) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[15] + mi := &file_misc_v1_misc_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1277,7 +1360,7 @@ func (x *CommentNewsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CommentNewsRequest.ProtoReflect.Descriptor instead. func (*CommentNewsRequest) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{15} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{16} } func (x *CommentNewsRequest) GetParentId() string { @@ -1315,13 +1398,6 @@ func (x *CommentNewsRequest) GetReplyQuote() string { return "" } -func (x *CommentNewsRequest) GetFeeSatPerVbyte() uint64 { - if x != nil { - return x.FeeSatPerVbyte - } - return 0 -} - func (x *CommentNewsRequest) GetFeeSats() uint64 { if x != nil { return x.FeeSats @@ -1338,7 +1414,7 @@ type CommentNewsResponse struct { func (x *CommentNewsResponse) Reset() { *x = CommentNewsResponse{} - mi := &file_misc_v1_misc_proto_msgTypes[16] + mi := &file_misc_v1_misc_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1350,7 +1426,7 @@ func (x *CommentNewsResponse) String() string { func (*CommentNewsResponse) ProtoMessage() {} func (x *CommentNewsResponse) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[16] + mi := &file_misc_v1_misc_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1363,7 +1439,7 @@ func (x *CommentNewsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CommentNewsResponse.ProtoReflect.Descriptor instead. func (*CommentNewsResponse) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{16} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{17} } func (x *CommentNewsResponse) GetTxid() string { @@ -1373,6 +1449,112 @@ func (x *CommentNewsResponse) GetTxid() string { return "" } +type ReactNewsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Hex-encoded 12-byte ItemID of the story or comment. + ParentId string `protobuf:"bytes,1,opt,name=parent_id,json=parentId,proto3" json:"parent_id,omitempty"` + Emoji string `protobuf:"bytes,2,opt,name=emoji,proto3" json:"emoji,omitempty"` + // Fee of the reaction. It adds to the total of the emoji. + FeeSats uint64 `protobuf:"varint,3,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReactNewsRequest) Reset() { + *x = ReactNewsRequest{} + mi := &file_misc_v1_misc_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReactNewsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReactNewsRequest) ProtoMessage() {} + +func (x *ReactNewsRequest) ProtoReflect() protoreflect.Message { + mi := &file_misc_v1_misc_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReactNewsRequest.ProtoReflect.Descriptor instead. +func (*ReactNewsRequest) Descriptor() ([]byte, []int) { + return file_misc_v1_misc_proto_rawDescGZIP(), []int{18} +} + +func (x *ReactNewsRequest) GetParentId() string { + if x != nil { + return x.ParentId + } + return "" +} + +func (x *ReactNewsRequest) GetEmoji() string { + if x != nil { + return x.Emoji + } + return "" +} + +func (x *ReactNewsRequest) GetFeeSats() uint64 { + if x != nil { + return x.FeeSats + } + return 0 +} + +type ReactNewsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Txid string `protobuf:"bytes,1,opt,name=txid,proto3" json:"txid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReactNewsResponse) Reset() { + *x = ReactNewsResponse{} + mi := &file_misc_v1_misc_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReactNewsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReactNewsResponse) ProtoMessage() {} + +func (x *ReactNewsResponse) ProtoReflect() protoreflect.Message { + mi := &file_misc_v1_misc_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReactNewsResponse.ProtoReflect.Descriptor instead. +func (*ReactNewsResponse) Descriptor() ([]byte, []int) { + return file_misc_v1_misc_proto_rawDescGZIP(), []int{19} +} + +func (x *ReactNewsResponse) GetTxid() string { + if x != nil { + return x.Txid + } + return "" +} + type ListCommentsRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Hex-encoded 12-byte ItemID whose reply thread to return. @@ -1383,7 +1565,7 @@ type ListCommentsRequest struct { func (x *ListCommentsRequest) Reset() { *x = ListCommentsRequest{} - mi := &file_misc_v1_misc_proto_msgTypes[17] + mi := &file_misc_v1_misc_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1395,7 +1577,7 @@ func (x *ListCommentsRequest) String() string { func (*ListCommentsRequest) ProtoMessage() {} func (x *ListCommentsRequest) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[17] + mi := &file_misc_v1_misc_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1408,7 +1590,7 @@ func (x *ListCommentsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListCommentsRequest.ProtoReflect.Descriptor instead. func (*ListCommentsRequest) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{17} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{20} } func (x *ListCommentsRequest) GetItemId() string { @@ -1442,7 +1624,7 @@ type Comment struct { func (x *Comment) Reset() { *x = Comment{} - mi := &file_misc_v1_misc_proto_msgTypes[18] + mi := &file_misc_v1_misc_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1454,7 +1636,7 @@ func (x *Comment) String() string { func (*Comment) ProtoMessage() {} func (x *Comment) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[18] + mi := &file_misc_v1_misc_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1467,7 +1649,7 @@ func (x *Comment) ProtoReflect() protoreflect.Message { // Deprecated: Use Comment.ProtoReflect.Descriptor instead. func (*Comment) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{18} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{21} } func (x *Comment) GetItemId() string { @@ -1551,7 +1733,7 @@ type ListCommentsResponse struct { func (x *ListCommentsResponse) Reset() { *x = ListCommentsResponse{} - mi := &file_misc_v1_misc_proto_msgTypes[19] + mi := &file_misc_v1_misc_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1563,7 +1745,7 @@ func (x *ListCommentsResponse) String() string { func (*ListCommentsResponse) ProtoMessage() {} func (x *ListCommentsResponse) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[19] + mi := &file_misc_v1_misc_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1576,7 +1758,7 @@ func (x *ListCommentsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListCommentsResponse.ProtoReflect.Descriptor instead. func (*ListCommentsResponse) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{19} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{22} } func (x *ListCommentsResponse) GetComments() []*Comment { @@ -1604,7 +1786,7 @@ type TimestampFileRequest struct { func (x *TimestampFileRequest) Reset() { *x = TimestampFileRequest{} - mi := &file_misc_v1_misc_proto_msgTypes[20] + mi := &file_misc_v1_misc_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1616,7 +1798,7 @@ func (x *TimestampFileRequest) String() string { func (*TimestampFileRequest) ProtoMessage() {} func (x *TimestampFileRequest) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[20] + mi := &file_misc_v1_misc_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1629,7 +1811,7 @@ func (x *TimestampFileRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use TimestampFileRequest.ProtoReflect.Descriptor instead. func (*TimestampFileRequest) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{20} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{23} } func (x *TimestampFileRequest) GetFilename() string { @@ -1657,7 +1839,7 @@ type TimestampFileResponse struct { func (x *TimestampFileResponse) Reset() { *x = TimestampFileResponse{} - mi := &file_misc_v1_misc_proto_msgTypes[21] + mi := &file_misc_v1_misc_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1669,7 +1851,7 @@ func (x *TimestampFileResponse) String() string { func (*TimestampFileResponse) ProtoMessage() {} func (x *TimestampFileResponse) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[21] + mi := &file_misc_v1_misc_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1682,7 +1864,7 @@ func (x *TimestampFileResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use TimestampFileResponse.ProtoReflect.Descriptor instead. func (*TimestampFileResponse) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{21} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{24} } func (x *TimestampFileResponse) GetId() int64 { @@ -1723,7 +1905,7 @@ type FileTimestamp struct { func (x *FileTimestamp) Reset() { *x = FileTimestamp{} - mi := &file_misc_v1_misc_proto_msgTypes[22] + mi := &file_misc_v1_misc_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1735,7 +1917,7 @@ func (x *FileTimestamp) String() string { func (*FileTimestamp) ProtoMessage() {} func (x *FileTimestamp) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[22] + mi := &file_misc_v1_misc_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1748,7 +1930,7 @@ func (x *FileTimestamp) ProtoReflect() protoreflect.Message { // Deprecated: Use FileTimestamp.ProtoReflect.Descriptor instead. func (*FileTimestamp) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{22} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{25} } func (x *FileTimestamp) GetId() int64 { @@ -1823,7 +2005,7 @@ type ListTimestampsResponse struct { func (x *ListTimestampsResponse) Reset() { *x = ListTimestampsResponse{} - mi := &file_misc_v1_misc_proto_msgTypes[23] + mi := &file_misc_v1_misc_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1835,7 +2017,7 @@ func (x *ListTimestampsResponse) String() string { func (*ListTimestampsResponse) ProtoMessage() {} func (x *ListTimestampsResponse) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[23] + mi := &file_misc_v1_misc_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1848,7 +2030,7 @@ func (x *ListTimestampsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTimestampsResponse.ProtoReflect.Descriptor instead. func (*ListTimestampsResponse) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{23} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{26} } func (x *ListTimestampsResponse) GetTimestamps() []*FileTimestamp { @@ -1868,7 +2050,7 @@ type VerifyTimestampRequest struct { func (x *VerifyTimestampRequest) Reset() { *x = VerifyTimestampRequest{} - mi := &file_misc_v1_misc_proto_msgTypes[24] + mi := &file_misc_v1_misc_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1880,7 +2062,7 @@ func (x *VerifyTimestampRequest) String() string { func (*VerifyTimestampRequest) ProtoMessage() {} func (x *VerifyTimestampRequest) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[24] + mi := &file_misc_v1_misc_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1893,7 +2075,7 @@ func (x *VerifyTimestampRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use VerifyTimestampRequest.ProtoReflect.Descriptor instead. func (*VerifyTimestampRequest) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{24} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{27} } func (x *VerifyTimestampRequest) GetFileData() []byte { @@ -1920,7 +2102,7 @@ type VerifyTimestampResponse struct { func (x *VerifyTimestampResponse) Reset() { *x = VerifyTimestampResponse{} - mi := &file_misc_v1_misc_proto_msgTypes[25] + mi := &file_misc_v1_misc_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1932,7 +2114,7 @@ func (x *VerifyTimestampResponse) String() string { func (*VerifyTimestampResponse) ProtoMessage() {} func (x *VerifyTimestampResponse) ProtoReflect() protoreflect.Message { - mi := &file_misc_v1_misc_proto_msgTypes[25] + mi := &file_misc_v1_misc_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1945,7 +2127,7 @@ func (x *VerifyTimestampResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use VerifyTimestampResponse.ProtoReflect.Descriptor instead. func (*VerifyTimestampResponse) Descriptor() ([]byte, []int) { - return file_misc_v1_misc_proto_rawDescGZIP(), []int{25} + return file_misc_v1_misc_proto_rawDescGZIP(), []int{28} } func (x *VerifyTimestampResponse) GetTimestamp() *FileTimestamp { @@ -2022,7 +2204,7 @@ const file_misc_v1_misc_proto_rawDesc = "" + "\x05topic\x18\x01 \x01(\tR\x05topic\x12\x1e\n" + "\n" + "subscribed\x18\x02 \x01(\bR\n" + - "subscribed\"\x8f\x02\n" + + "subscribed\"\xa5\x02\n" + "\x16EstimateNewsFeeRequest\x12+\n" + "\x06action\x18\x01 \x01(\x0e2\x13.misc.v1.NewsActionR\x06action\x12\x12\n" + "\x04body\x18\x02 \x01(\tR\x04body\x12\x1a\n" + @@ -2033,14 +2215,16 @@ const file_misc_v1_misc_proto_rawDesc = "" + "\x04nsfw\x18\a \x01(\bR\x04nsfw\x12\x1d\n" + "\n" + "topic_name\x18\b \x01(\tR\ttopicName\x12%\n" + - "\x0eretention_days\x18\t \x01(\x05R\rretentionDays\"u\n" + + "\x0eretention_days\x18\t \x01(\x05R\rretentionDays\x12\x14\n" + + "\x05emoji\x18\n" + + " \x01(\tR\x05emoji\"u\n" + "\x17EstimateNewsFeeResponse\x12\x14\n" + "\x05vsize\x18\x01 \x01(\x04R\x05vsize\x12)\n" + "\x11fee_sat_per_vbyte\x18\x02 \x01(\x01R\x0efeeSatPerVbyte\x12\x19\n" + "\bfee_sats\x18\x03 \x01(\x04R\afeeSats\":\n" + "\x13ListCoinNewsRequest\x12\x19\n" + "\x05topic\x18\x01 \x01(\tH\x00R\x05topic\x88\x01\x01B\b\n" + - "\x06_topic\"\xa2\x03\n" + + "\x06_topic\"\xff\x03\n" + "\bCoinNews\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" + "\x05topic\x18\x02 \x01(\tR\x05topic\x12\x1a\n" + @@ -2056,22 +2240,32 @@ const file_misc_v1_misc_proto_rawDesc = "" + "\x04txid\x18\x0e \x01(\tR\x04txid\x12\x12\n" + "\x04vout\x18\x0f \x01(\rR\x04vout\x12\x1a\n" + "\boutdated\x18\x10 \x01(\bR\boutdated\x12\x18\n" + - "\apending\x18\x11 \x01(\bR\apendingJ\x04\b\b\x10\tJ\x04\b\t\x10\n" + + "\apending\x18\x11 \x01(\bR\apending\x12/\n" + + "\treactions\x18\x12 \x03(\v2\x11.misc.v1.ReactionR\treactions\x12*\n" + + "\x11max_comment_chars\x18\x13 \x01(\x05R\x0fmaxCommentCharsJ\x04\b\b\x10\tJ\x04\b\t\x10\n" + "J\x04\b\n" + - "\x10\vR\aupvotesR\tdownvotesR\x05score\"k\n" + + "\x10\vR\aupvotesR\tdownvotesR\x05score\";\n" + + "\bReaction\x12\x14\n" + + "\x05emoji\x18\x01 \x01(\tR\x05emoji\x12\x19\n" + + "\bfee_sats\x18\x02 \x01(\x03R\afeeSats\"k\n" + "\x14ListCoinNewsResponse\x12.\n" + "\tcoin_news\x18\x01 \x03(\v2\x11.misc.v1.CoinNewsR\bcoinNews\x12#\n" + - "\rindexer_error\x18\x02 \x01(\tR\findexerError\"\xd2\x01\n" + + "\rindexer_error\x18\x02 \x01(\tR\findexerError\"\xc0\x01\n" + "\x12CommentNewsRequest\x12\x1b\n" + "\tparent_id\x18\x01 \x01(\tR\bparentId\x12\x12\n" + "\x04body\x18\x02 \x01(\tR\x04body\x12\x10\n" + "\x03url\x18\x03 \x01(\tR\x03url\x12\x12\n" + "\x04lang\x18\x04 \x01(\tR\x04lang\x12\x1f\n" + "\vreply_quote\x18\x05 \x01(\tR\n" + - "replyQuote\x12)\n" + - "\x11fee_sat_per_vbyte\x18\x06 \x01(\x04R\x0efeeSatPerVbyte\x12\x19\n" + - "\bfee_sats\x18\a \x01(\x04R\afeeSats\")\n" + + "replyQuote\x12\x19\n" + + "\bfee_sats\x18\a \x01(\x04R\afeeSatsJ\x04\b\x06\x10\aR\x11fee_sat_per_vbyte\")\n" + "\x13CommentNewsResponse\x12\x12\n" + + "\x04txid\x18\x01 \x01(\tR\x04txid\"`\n" + + "\x10ReactNewsRequest\x12\x1b\n" + + "\tparent_id\x18\x01 \x01(\tR\bparentId\x12\x14\n" + + "\x05emoji\x18\x02 \x01(\tR\x05emoji\x12\x19\n" + + "\bfee_sats\x18\x03 \x01(\x04R\afeeSats\"'\n" + + "\x11ReactNewsResponse\x12\x12\n" + "\x04txid\x18\x01 \x01(\tR\x04txid\".\n" + "\x13ListCommentsRequest\x12\x17\n" + "\aitem_id\x18\x01 \x01(\tR\x06itemId\"\xd1\x02\n" + @@ -2131,13 +2325,14 @@ const file_misc_v1_misc_proto_rawDesc = "" + "\x15OP_RETURN_SORT_HEIGHT\x10\x02\x12\x16\n" + "\x12OP_RETURN_SORT_FEE\x10\x03\x12\x17\n" + "\x13OP_RETURN_SORT_TXID\x10\x04\x12\x1a\n" + - "\x16OP_RETURN_SORT_MESSAGE\x10\x05*\x88\x01\n" + + "\x16OP_RETURN_SORT_MESSAGE\x10\x05*\xa2\x01\n" + "\n" + "NewsAction\x12\x1b\n" + "\x17NEWS_ACTION_UNSPECIFIED\x10\x00\x12\x17\n" + "\x13NEWS_ACTION_COMMENT\x10\x02\x12\x15\n" + "\x11NEWS_ACTION_STORY\x10\x03\x12\x15\n" + - "\x11NEWS_ACTION_TOPIC\x10\x04\"\x04\b\x01\x10\x01*\x10NEWS_ACTION_VOTE2\xfc\a\n" + + "\x11NEWS_ACTION_TOPIC\x10\x04\x12\x18\n" + + "\x14NEWS_ACTION_REACTION\x10\x05\"\x04\b\x01\x10\x01*\x10NEWS_ACTION_VOTE2\xc0\b\n" + "\vMiscService\x12K\n" + "\fListOPReturn\x12\x1c.misc.v1.ListOPReturnRequest\x1a\x1d.misc.v1.ListOPReturnResponse\x12N\n" + "\rBroadcastNews\x12\x1d.misc.v1.BroadcastNewsRequest\x1a\x1e.misc.v1.BroadcastNewsResponse\x12H\n" + @@ -2148,7 +2343,8 @@ const file_misc_v1_misc_proto_rawDesc = "" + "\x12SetTopicSubscribed\x12\".misc.v1.SetTopicSubscribedRequest\x1a\x16.google.protobuf.Empty\x12K\n" + "\fListCoinNews\x12\x1c.misc.v1.ListCoinNewsRequest\x1a\x1d.misc.v1.ListCoinNewsResponse\x12H\n" + "\vCommentNews\x12\x1b.misc.v1.CommentNewsRequest\x1a\x1c.misc.v1.CommentNewsResponse\x12K\n" + - "\fListComments\x12\x1c.misc.v1.ListCommentsRequest\x1a\x1d.misc.v1.ListCommentsResponse\x12T\n" + + "\fListComments\x12\x1c.misc.v1.ListCommentsRequest\x1a\x1d.misc.v1.ListCommentsResponse\x12B\n" + + "\tReactNews\x12\x19.misc.v1.ReactNewsRequest\x1a\x1a.misc.v1.ReactNewsResponse\x12T\n" + "\x0fEstimateNewsFee\x12\x1f.misc.v1.EstimateNewsFeeRequest\x1a .misc.v1.EstimateNewsFeeResponse\x12N\n" + "\rTimestampFile\x12\x1d.misc.v1.TimestampFileRequest\x1a\x1e.misc.v1.TimestampFileResponse\x12I\n" + "\x0eListTimestamps\x12\x16.google.protobuf.Empty\x1a\x1f.misc.v1.ListTimestampsResponse\x12T\n" + @@ -2168,7 +2364,7 @@ func file_misc_v1_misc_proto_rawDescGZIP() []byte { } var file_misc_v1_misc_proto_enumTypes = make([]protoimpl.EnumInfo, 2) -var file_misc_v1_misc_proto_msgTypes = make([]protoimpl.MessageInfo, 26) +var file_misc_v1_misc_proto_msgTypes = make([]protoimpl.MessageInfo, 29) var file_misc_v1_misc_proto_goTypes = []any{ (OPReturnSort)(0), // 0: misc.v1.OPReturnSort (NewsAction)(0), // 1: misc.v1.NewsAction @@ -2186,69 +2382,75 @@ var file_misc_v1_misc_proto_goTypes = []any{ (*EstimateNewsFeeResponse)(nil), // 13: misc.v1.EstimateNewsFeeResponse (*ListCoinNewsRequest)(nil), // 14: misc.v1.ListCoinNewsRequest (*CoinNews)(nil), // 15: misc.v1.CoinNews - (*ListCoinNewsResponse)(nil), // 16: misc.v1.ListCoinNewsResponse - (*CommentNewsRequest)(nil), // 17: misc.v1.CommentNewsRequest - (*CommentNewsResponse)(nil), // 18: misc.v1.CommentNewsResponse - (*ListCommentsRequest)(nil), // 19: misc.v1.ListCommentsRequest - (*Comment)(nil), // 20: misc.v1.Comment - (*ListCommentsResponse)(nil), // 21: misc.v1.ListCommentsResponse - (*TimestampFileRequest)(nil), // 22: misc.v1.TimestampFileRequest - (*TimestampFileResponse)(nil), // 23: misc.v1.TimestampFileResponse - (*FileTimestamp)(nil), // 24: misc.v1.FileTimestamp - (*ListTimestampsResponse)(nil), // 25: misc.v1.ListTimestampsResponse - (*VerifyTimestampRequest)(nil), // 26: misc.v1.VerifyTimestampRequest - (*VerifyTimestampResponse)(nil), // 27: misc.v1.VerifyTimestampResponse - (*timestamppb.Timestamp)(nil), // 28: google.protobuf.Timestamp - (*emptypb.Empty)(nil), // 29: google.protobuf.Empty + (*Reaction)(nil), // 16: misc.v1.Reaction + (*ListCoinNewsResponse)(nil), // 17: misc.v1.ListCoinNewsResponse + (*CommentNewsRequest)(nil), // 18: misc.v1.CommentNewsRequest + (*CommentNewsResponse)(nil), // 19: misc.v1.CommentNewsResponse + (*ReactNewsRequest)(nil), // 20: misc.v1.ReactNewsRequest + (*ReactNewsResponse)(nil), // 21: misc.v1.ReactNewsResponse + (*ListCommentsRequest)(nil), // 22: misc.v1.ListCommentsRequest + (*Comment)(nil), // 23: misc.v1.Comment + (*ListCommentsResponse)(nil), // 24: misc.v1.ListCommentsResponse + (*TimestampFileRequest)(nil), // 25: misc.v1.TimestampFileRequest + (*TimestampFileResponse)(nil), // 26: misc.v1.TimestampFileResponse + (*FileTimestamp)(nil), // 27: misc.v1.FileTimestamp + (*ListTimestampsResponse)(nil), // 28: misc.v1.ListTimestampsResponse + (*VerifyTimestampRequest)(nil), // 29: misc.v1.VerifyTimestampRequest + (*VerifyTimestampResponse)(nil), // 30: misc.v1.VerifyTimestampResponse + (*timestamppb.Timestamp)(nil), // 31: google.protobuf.Timestamp + (*emptypb.Empty)(nil), // 32: google.protobuf.Empty } var file_misc_v1_misc_proto_depIdxs = []int32{ - 28, // 0: misc.v1.ListOPReturnRequest.from:type_name -> google.protobuf.Timestamp - 28, // 1: misc.v1.ListOPReturnRequest.to:type_name -> google.protobuf.Timestamp + 31, // 0: misc.v1.ListOPReturnRequest.from:type_name -> google.protobuf.Timestamp + 31, // 1: misc.v1.ListOPReturnRequest.to:type_name -> google.protobuf.Timestamp 0, // 2: misc.v1.ListOPReturnRequest.sort:type_name -> misc.v1.OPReturnSort 4, // 3: misc.v1.ListOPReturnResponse.op_returns:type_name -> misc.v1.OPReturn - 28, // 4: misc.v1.OPReturn.create_time:type_name -> google.protobuf.Timestamp - 28, // 5: misc.v1.Topic.create_time:type_name -> google.protobuf.Timestamp + 31, // 4: misc.v1.OPReturn.create_time:type_name -> google.protobuf.Timestamp + 31, // 5: misc.v1.Topic.create_time:type_name -> google.protobuf.Timestamp 9, // 6: misc.v1.ListTopicsResponse.topics:type_name -> misc.v1.Topic 1, // 7: misc.v1.EstimateNewsFeeRequest.action:type_name -> misc.v1.NewsAction - 28, // 8: misc.v1.CoinNews.create_time:type_name -> google.protobuf.Timestamp - 15, // 9: misc.v1.ListCoinNewsResponse.coin_news:type_name -> misc.v1.CoinNews - 28, // 10: misc.v1.Comment.create_time:type_name -> google.protobuf.Timestamp - 20, // 11: misc.v1.ListCommentsResponse.comments:type_name -> misc.v1.Comment - 28, // 12: misc.v1.FileTimestamp.created_at:type_name -> google.protobuf.Timestamp - 28, // 13: misc.v1.FileTimestamp.confirmed_at:type_name -> google.protobuf.Timestamp - 24, // 14: misc.v1.ListTimestampsResponse.timestamps:type_name -> misc.v1.FileTimestamp - 24, // 15: misc.v1.VerifyTimestampResponse.timestamp:type_name -> misc.v1.FileTimestamp - 2, // 16: misc.v1.MiscService.ListOPReturn:input_type -> misc.v1.ListOPReturnRequest - 5, // 17: misc.v1.MiscService.BroadcastNews:input_type -> misc.v1.BroadcastNewsRequest - 7, // 18: misc.v1.MiscService.CreateTopic:input_type -> misc.v1.CreateTopicRequest - 29, // 19: misc.v1.MiscService.ListTopics:input_type -> google.protobuf.Empty - 29, // 20: misc.v1.MiscService.ListChainTopics:input_type -> google.protobuf.Empty - 11, // 21: misc.v1.MiscService.SetTopicSubscribed:input_type -> misc.v1.SetTopicSubscribedRequest - 14, // 22: misc.v1.MiscService.ListCoinNews:input_type -> misc.v1.ListCoinNewsRequest - 17, // 23: misc.v1.MiscService.CommentNews:input_type -> misc.v1.CommentNewsRequest - 19, // 24: misc.v1.MiscService.ListComments:input_type -> misc.v1.ListCommentsRequest - 12, // 25: misc.v1.MiscService.EstimateNewsFee:input_type -> misc.v1.EstimateNewsFeeRequest - 22, // 26: misc.v1.MiscService.TimestampFile:input_type -> misc.v1.TimestampFileRequest - 29, // 27: misc.v1.MiscService.ListTimestamps:input_type -> google.protobuf.Empty - 26, // 28: misc.v1.MiscService.VerifyTimestamp:input_type -> misc.v1.VerifyTimestampRequest - 3, // 29: misc.v1.MiscService.ListOPReturn:output_type -> misc.v1.ListOPReturnResponse - 6, // 30: misc.v1.MiscService.BroadcastNews:output_type -> misc.v1.BroadcastNewsResponse - 8, // 31: misc.v1.MiscService.CreateTopic:output_type -> misc.v1.CreateTopicResponse - 10, // 32: misc.v1.MiscService.ListTopics:output_type -> misc.v1.ListTopicsResponse - 10, // 33: misc.v1.MiscService.ListChainTopics:output_type -> misc.v1.ListTopicsResponse - 29, // 34: misc.v1.MiscService.SetTopicSubscribed:output_type -> google.protobuf.Empty - 16, // 35: misc.v1.MiscService.ListCoinNews:output_type -> misc.v1.ListCoinNewsResponse - 18, // 36: misc.v1.MiscService.CommentNews:output_type -> misc.v1.CommentNewsResponse - 21, // 37: misc.v1.MiscService.ListComments:output_type -> misc.v1.ListCommentsResponse - 13, // 38: misc.v1.MiscService.EstimateNewsFee:output_type -> misc.v1.EstimateNewsFeeResponse - 23, // 39: misc.v1.MiscService.TimestampFile:output_type -> misc.v1.TimestampFileResponse - 25, // 40: misc.v1.MiscService.ListTimestamps:output_type -> misc.v1.ListTimestampsResponse - 27, // 41: misc.v1.MiscService.VerifyTimestamp:output_type -> misc.v1.VerifyTimestampResponse - 29, // [29:42] is the sub-list for method output_type - 16, // [16:29] is the sub-list for method input_type - 16, // [16:16] is the sub-list for extension type_name - 16, // [16:16] is the sub-list for extension extendee - 0, // [0:16] is the sub-list for field type_name + 31, // 8: misc.v1.CoinNews.create_time:type_name -> google.protobuf.Timestamp + 16, // 9: misc.v1.CoinNews.reactions:type_name -> misc.v1.Reaction + 15, // 10: misc.v1.ListCoinNewsResponse.coin_news:type_name -> misc.v1.CoinNews + 31, // 11: misc.v1.Comment.create_time:type_name -> google.protobuf.Timestamp + 23, // 12: misc.v1.ListCommentsResponse.comments:type_name -> misc.v1.Comment + 31, // 13: misc.v1.FileTimestamp.created_at:type_name -> google.protobuf.Timestamp + 31, // 14: misc.v1.FileTimestamp.confirmed_at:type_name -> google.protobuf.Timestamp + 27, // 15: misc.v1.ListTimestampsResponse.timestamps:type_name -> misc.v1.FileTimestamp + 27, // 16: misc.v1.VerifyTimestampResponse.timestamp:type_name -> misc.v1.FileTimestamp + 2, // 17: misc.v1.MiscService.ListOPReturn:input_type -> misc.v1.ListOPReturnRequest + 5, // 18: misc.v1.MiscService.BroadcastNews:input_type -> misc.v1.BroadcastNewsRequest + 7, // 19: misc.v1.MiscService.CreateTopic:input_type -> misc.v1.CreateTopicRequest + 32, // 20: misc.v1.MiscService.ListTopics:input_type -> google.protobuf.Empty + 32, // 21: misc.v1.MiscService.ListChainTopics:input_type -> google.protobuf.Empty + 11, // 22: misc.v1.MiscService.SetTopicSubscribed:input_type -> misc.v1.SetTopicSubscribedRequest + 14, // 23: misc.v1.MiscService.ListCoinNews:input_type -> misc.v1.ListCoinNewsRequest + 18, // 24: misc.v1.MiscService.CommentNews:input_type -> misc.v1.CommentNewsRequest + 22, // 25: misc.v1.MiscService.ListComments:input_type -> misc.v1.ListCommentsRequest + 20, // 26: misc.v1.MiscService.ReactNews:input_type -> misc.v1.ReactNewsRequest + 12, // 27: misc.v1.MiscService.EstimateNewsFee:input_type -> misc.v1.EstimateNewsFeeRequest + 25, // 28: misc.v1.MiscService.TimestampFile:input_type -> misc.v1.TimestampFileRequest + 32, // 29: misc.v1.MiscService.ListTimestamps:input_type -> google.protobuf.Empty + 29, // 30: misc.v1.MiscService.VerifyTimestamp:input_type -> misc.v1.VerifyTimestampRequest + 3, // 31: misc.v1.MiscService.ListOPReturn:output_type -> misc.v1.ListOPReturnResponse + 6, // 32: misc.v1.MiscService.BroadcastNews:output_type -> misc.v1.BroadcastNewsResponse + 8, // 33: misc.v1.MiscService.CreateTopic:output_type -> misc.v1.CreateTopicResponse + 10, // 34: misc.v1.MiscService.ListTopics:output_type -> misc.v1.ListTopicsResponse + 10, // 35: misc.v1.MiscService.ListChainTopics:output_type -> misc.v1.ListTopicsResponse + 32, // 36: misc.v1.MiscService.SetTopicSubscribed:output_type -> google.protobuf.Empty + 17, // 37: misc.v1.MiscService.ListCoinNews:output_type -> misc.v1.ListCoinNewsResponse + 19, // 38: misc.v1.MiscService.CommentNews:output_type -> misc.v1.CommentNewsResponse + 24, // 39: misc.v1.MiscService.ListComments:output_type -> misc.v1.ListCommentsResponse + 21, // 40: misc.v1.MiscService.ReactNews:output_type -> misc.v1.ReactNewsResponse + 13, // 41: misc.v1.MiscService.EstimateNewsFee:output_type -> misc.v1.EstimateNewsFeeResponse + 26, // 42: misc.v1.MiscService.TimestampFile:output_type -> misc.v1.TimestampFileResponse + 28, // 43: misc.v1.MiscService.ListTimestamps:output_type -> misc.v1.ListTimestampsResponse + 30, // 44: misc.v1.MiscService.VerifyTimestamp:output_type -> misc.v1.VerifyTimestampResponse + 31, // [31:45] is the sub-list for method output_type + 17, // [17:31] is the sub-list for method input_type + 17, // [17:17] is the sub-list for extension type_name + 17, // [17:17] is the sub-list for extension extendee + 0, // [0:17] is the sub-list for field type_name } func init() { file_misc_v1_misc_proto_init() } @@ -2258,15 +2460,15 @@ func file_misc_v1_misc_proto_init() { } file_misc_v1_misc_proto_msgTypes[2].OneofWrappers = []any{} file_misc_v1_misc_proto_msgTypes[12].OneofWrappers = []any{} - file_misc_v1_misc_proto_msgTypes[22].OneofWrappers = []any{} - file_misc_v1_misc_proto_msgTypes[24].OneofWrappers = []any{} + file_misc_v1_misc_proto_msgTypes[25].OneofWrappers = []any{} + file_misc_v1_misc_proto_msgTypes[27].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_misc_v1_misc_proto_rawDesc), len(file_misc_v1_misc_proto_rawDesc)), NumEnums: 2, - NumMessages: 26, + NumMessages: 29, NumExtensions: 0, NumServices: 1, }, diff --git a/bitwindow/server/gen/misc/v1/miscv1connect/misc.connect.go b/bitwindow/server/gen/misc/v1/miscv1connect/misc.connect.go index fd49189f90..ceea6acdaa 100644 --- a/bitwindow/server/gen/misc/v1/miscv1connect/misc.connect.go +++ b/bitwindow/server/gen/misc/v1/miscv1connect/misc.connect.go @@ -45,6 +45,8 @@ const ( MiscServiceCommentNewsProcedure = "/misc.v1.MiscService/CommentNews" // MiscServiceListCommentsProcedure is the procedure name of the MiscService's ListComments RPC. MiscServiceListCommentsProcedure = "/misc.v1.MiscService/ListComments" + // MiscServiceReactNewsProcedure is the procedure name of the MiscService's ReactNews RPC. + MiscServiceReactNewsProcedure = "/misc.v1.MiscService/ReactNews" // MiscServiceEstimateNewsFeeProcedure is the procedure name of the MiscService's EstimateNewsFee // RPC. MiscServiceEstimateNewsFeeProcedure = "/misc.v1.MiscService/EstimateNewsFee" @@ -121,6 +123,13 @@ var ( Procedure: MiscServiceListCommentsProcedure, } }) + miscServiceReactNewsSpec = sync.OnceValue(func() connect.Spec { + return connect.Spec{ + StreamType: connect.StreamTypeUnary, + Schema: v1.File_misc_v1_misc_proto.Services().ByName("MiscService").Methods().ByName("ReactNews"), + Procedure: MiscServiceReactNewsProcedure, + } + }) miscServiceEstimateNewsFeeSpec = sync.OnceValue(func() connect.Spec { return connect.Spec{ StreamType: connect.StreamTypeUnary, @@ -169,6 +178,8 @@ type MiscServiceClient interface { CommentNews(context.Context, *v1.CommentNewsRequest) (*v1.CommentNewsResponse, error) // Returns the full reply thread rooted at an Item, highest fee first. ListComments(context.Context, *v1.ListCommentsRequest) (*v1.ListCommentsResponse, error) + // Broadcasts a Reaction (CoinNews Reaction, 0x07) on an Item. + ReactNews(context.Context, *v1.ReactNewsRequest) (*v1.ReactNewsResponse, error) // The fee that the active wallet pays for a story, a comment or a topic with no fee // choice. Broadcasts nothing. EstimateNewsFee(context.Context, *v1.EstimateNewsFeeRequest) (*v1.EstimateNewsFeeResponse, error) @@ -202,6 +213,8 @@ type MiscServiceHandler interface { CommentNews(context.Context, *v1.CommentNewsRequest) (*v1.CommentNewsResponse, error) // Returns the full reply thread rooted at an Item, highest fee first. ListComments(context.Context, *v1.ListCommentsRequest) (*v1.ListCommentsResponse, error) + // Broadcasts a Reaction (CoinNews Reaction, 0x07) on an Item. + ReactNews(context.Context, *v1.ReactNewsRequest) (*v1.ReactNewsResponse, error) // The fee that the active wallet pays for a story, a comment or a topic with no fee // choice. Broadcasts nothing. EstimateNewsFee(context.Context, *v1.EstimateNewsFeeRequest) (*v1.EstimateNewsFeeResponse, error) @@ -224,6 +237,7 @@ func RegisterMiscServiceHandler(server *connect.Server, svc MiscServiceHandler) connect.Method{Spec: miscServiceListCoinNewsSpec(), Handler: adapter.listCoinNews}, connect.Method{Spec: miscServiceCommentNewsSpec(), Handler: adapter.commentNews}, connect.Method{Spec: miscServiceListCommentsSpec(), Handler: adapter.listComments}, + connect.Method{Spec: miscServiceReactNewsSpec(), Handler: adapter.reactNews}, connect.Method{Spec: miscServiceEstimateNewsFeeSpec(), Handler: adapter.estimateNewsFee}, connect.Method{Spec: miscServiceTimestampFileSpec(), Handler: adapter.timestampFile}, connect.Method{Spec: miscServiceListTimestampsSpec(), Handler: adapter.listTimestamps}, @@ -270,6 +284,10 @@ func (UnimplementedMiscServiceHandler) ListComments(context.Context, *v1.ListCom return nil, connect.NewError(connect.CodeUnimplemented, "misc.v1.MiscService.ListComments is not implemented") } +func (UnimplementedMiscServiceHandler) ReactNews(context.Context, *v1.ReactNewsRequest) (*v1.ReactNewsResponse, error) { + return nil, connect.NewError(connect.CodeUnimplemented, "misc.v1.MiscService.ReactNews is not implemented") +} + func (UnimplementedMiscServiceHandler) EstimateNewsFee(context.Context, *v1.EstimateNewsFeeRequest) (*v1.EstimateNewsFeeResponse, error) { return nil, connect.NewError(connect.CodeUnimplemented, "misc.v1.MiscService.EstimateNewsFee is not implemented") } @@ -362,6 +380,14 @@ func (c *miscServiceClient) ListComments(ctx context.Context, req *v1.ListCommen return &res, nil } +func (c *miscServiceClient) ReactNews(ctx context.Context, req *v1.ReactNewsRequest) (*v1.ReactNewsResponse, error) { + var res v1.ReactNewsResponse + if err := c.client.CallUnary(ctx, miscServiceReactNewsSpec(), req, &res); err != nil { + return nil, err + } + return &res, nil +} + func (c *miscServiceClient) EstimateNewsFee(ctx context.Context, req *v1.EstimateNewsFeeRequest) (*v1.EstimateNewsFeeResponse, error) { var res v1.EstimateNewsFeeResponse if err := c.client.CallUnary(ctx, miscServiceEstimateNewsFeeSpec(), req, &res); err != nil { @@ -504,6 +530,18 @@ func (h miscServiceHandler) listComments(ctx context.Context, _ connect.Spec, st return stream.Send(res) } +func (h miscServiceHandler) reactNews(ctx context.Context, _ connect.Spec, stream connect.ServerStream) error { + var req v1.ReactNewsRequest + if err := stream.Receive(&req); err != nil { + return err + } + res, err := h.svc.ReactNews(ctx, &req) + if err != nil { + return err + } + return stream.Send(res) +} + func (h miscServiceHandler) estimateNewsFee(ctx context.Context, _ connect.Spec, stream connect.ServerStream) error { var req v1.EstimateNewsFeeRequest if err := stream.Receive(&req); err != nil { diff --git a/bitwindow/server/models/coinnews/store.go b/bitwindow/server/models/coinnews/store.go index ef06fd1332..beea7b92bd 100644 --- a/bitwindow/server/models/coinnews/store.go +++ b/bitwindow/server/models/coinnews/store.go @@ -149,15 +149,16 @@ type BlockPos struct { type IndexEnv struct { Pos BlockPos TypeTag codec.TypeTag - Msg any // *codec.TopicCreation | *codec.Story | *codec.Comment | *codec.Continuation + Msg any // *codec.TopicCreation | *codec.Story | *codec.Comment | *codec.Continuation | *codec.Reaction } // ItemRef is an indexed Item's canonical scan position (spec §4.2): // (block_height, tx_index, vout_index). type ItemRef struct { - BlockHeight uint32 `db:"block_height"` - TxIndex uint32 `db:"tx_index"` - VoutIndex uint32 `db:"vout_index"` + BlockHeight uint32 `db:"block_height"` + TxIndex uint32 `db:"tx_index"` + VoutIndex uint32 `db:"vout_index"` + TypeTag codec.TypeTag `db:"type_tag"` } // Before reports whether a is strictly earlier than b in canonical scan @@ -178,7 +179,7 @@ func (a ItemRef) Before(b ItemRef) bool { // dropped (spec §4.1, §7, §8). func ResolveItem(ctx context.Context, db *sql.DB, id codec.ItemID) (ItemRef, bool, error) { ref, err := database.Get[ItemRef](ctx, db, - `SELECT block_height, tx_index, vout_index FROM cn_items WHERE item_id = ?`, + `SELECT block_height, tx_index, vout_index, type_tag FROM cn_items WHERE item_id = ?`, id[:], ) switch { @@ -191,6 +192,97 @@ func ResolveItem(ctx context.Context, db *sql.DB, id codec.ItemID) (ItemRef, boo } } +// RootStory walks up the comment chain from id to its Story (spec §7.1). +// It returns false when the chain ends at no Story. +func RootStory(ctx context.Context, db *sql.DB, id codec.ItemID) (codec.StoryRules, bool, error) { + type row struct { + FeeSats int64 `db:"fee_sats"` + Headline string `db:"headline"` + Body string `db:"body"` + } + r, err := database.Get[row](ctx, db, ` + WITH RECURSIVE up(id) AS ( + SELECT ? + UNION ALL + SELECT c.parent_id FROM cn_comments c JOIN up ON c.item_id = up.id + ) + SELECT COALESCE(o.fee_sats, 0) AS fee_sats, s.headline, COALESCE(s.body, '') AS body + FROM up + JOIN cn_stories s ON s.item_id = up.id + JOIN cn_items i ON i.item_id = s.item_id + LEFT JOIN op_returns o ON o.txid = i.txid AND o.vout = i.vout + `, id[:]) + switch { + case errors.Is(err, sql.ErrNoRows): + return codec.StoryRules{}, false, nil + case err != nil: + return codec.StoryRules{}, false, fmt.Errorf("coinnews: root story: %w", err) + } + return codec.StoryRules{FeeSats: r.FeeSats, Headline: r.Headline, Body: r.Body}, true, nil +} + +// StoryRulesOf returns what spec §7.1 reads from each indexed Story, by hex ItemID. +func StoryRulesOf(ctx context.Context, db *sql.DB) (map[string]codec.StoryRules, error) { + type row struct { + ItemID string `db:"item_id"` + FeeSats int64 `db:"fee_sats"` + Headline string `db:"headline"` + Body string `db:"body"` + } + rows, err := database.Select[row](ctx, db, ` + SELECT lower(hex(s.item_id)) AS item_id, COALESCE(o.fee_sats, 0) AS fee_sats, + s.headline, COALESCE(s.body, '') AS body + FROM cn_stories s + JOIN cn_items i ON i.item_id = s.item_id + LEFT JOIN op_returns o ON o.txid = i.txid AND o.vout = i.vout + `) + if err != nil { + return nil, fmt.Errorf("coinnews: story rules: %w", err) + } + out := make(map[string]codec.StoryRules, len(rows)) + for _, r := range rows { + out[r.ItemID] = codec.StoryRules{FeeSats: r.FeeSats, Headline: r.Headline, Body: r.Body} + } + return out, nil +} + +// TxFee returns the fee of a transaction with an OP_RETURN, 0 when unknown. +func TxFee(ctx context.Context, db *sql.DB, txid string) (int64, error) { + fee, err := database.Get[int64](ctx, db, + `SELECT COALESCE(MAX(fee_sats), 0) FROM op_returns WHERE txid = ?`, txid) + if err != nil { + return 0, fmt.Errorf("coinnews: fee of %s: %w", txid, err) + } + return fee, nil +} + +// Reaction is the fee total of one emoji on an Item (spec §8). +type Reaction struct { + ParentID string `db:"parent_id"` + Emoji string `db:"emoji"` + FeeSats int64 `db:"fee_sats"` +} + +// ListReactions returns the reactions of every Item by hex ItemID, highest total first. +func ListReactions(ctx context.Context, db *sql.DB) (map[string][]Reaction, error) { + rows, err := database.Select[Reaction](ctx, db, ` + SELECT lower(hex(r.parent_id)) AS parent_id, r.emoji, SUM(COALESCE(o.fee_sats, 0)) AS fee_sats + FROM cn_reactions r + JOIN cn_items i ON i.item_id = r.item_id + LEFT JOIN op_returns o ON o.txid = i.txid AND o.vout = i.vout + GROUP BY r.parent_id, r.emoji + ORDER BY fee_sats DESC, r.emoji ASC + `) + if err != nil { + return nil, fmt.Errorf("coinnews: list reactions: %w", err) + } + out := map[string][]Reaction{} + for _, r := range rows { + out[r.ParentID] = append(out[r.ParentID], r) + } + return out, nil +} + // Index writes one decoded CoinNews message. It is idempotent on (txid, vout). // The caller must verify the signatures and the references first (spec §4.1). func Index(ctx context.Context, db *sql.DB, env IndexEnv) error { @@ -222,6 +314,12 @@ func Index(ctx context.Context, db *sql.DB, env IndexEnv) error { if err := indexContinuation(ctx, tx, env.Pos, m); err != nil { return err } + case *codec.Reaction: + if _, err := tx.ExecContext(ctx, ` + INSERT OR IGNORE INTO cn_reactions (item_id, parent_id, emoji) VALUES (?, ?, ?) + `, itemID[:], m.Parent[:], m.Emoji); err != nil { + return fmt.Errorf("coinnews: insert cn_reactions: %w", err) + } default: return fmt.Errorf("coinnews: unhandled message type %T", env.Msg) } diff --git a/bitwindow/server/proto/misc/v1/misc.proto b/bitwindow/server/proto/misc/v1/misc.proto index 7635107dc1..b8ec922cc5 100644 --- a/bitwindow/server/proto/misc/v1/misc.proto +++ b/bitwindow/server/proto/misc/v1/misc.proto @@ -22,6 +22,8 @@ service MiscService { rpc CommentNews(CommentNewsRequest) returns (CommentNewsResponse); // Returns the full reply thread rooted at an Item, highest fee first. rpc ListComments(ListCommentsRequest) returns (ListCommentsResponse); + // Broadcasts a Reaction (CoinNews Reaction, 0x07) on an Item. + rpc ReactNews(ReactNewsRequest) returns (ReactNewsResponse); // The fee that the active wallet pays for a story, a comment or a topic with no fee // choice. Broadcasts nothing. rpc EstimateNewsFee(EstimateNewsFeeRequest) returns (EstimateNewsFeeResponse); @@ -131,6 +133,7 @@ enum NewsAction { NEWS_ACTION_COMMENT = 2; NEWS_ACTION_STORY = 3; NEWS_ACTION_TOPIC = 4; + NEWS_ACTION_REACTION = 5; } message EstimateNewsFeeRequest { @@ -146,6 +149,8 @@ message EstimateNewsFeeRequest { // Topic fields that change the size of the payload. string topic_name = 8; int32 retention_days = 9; + // Reaction field that changes the size of the payload. + string emoji = 10; } message EstimateNewsFeeResponse { @@ -187,6 +192,17 @@ message CoinNews { // True for a story in the mempool. Its create_time is the time that the // node first saw it, and it has no item_id. bool pending = 17; + // Reactions to the story, highest total first. + repeated Reaction reactions = 18; + // The most characters a comment on this story can hold (spec §7.1). + int32 max_comment_chars = 19; +} + +// The fee total of one emoji on an item. +message Reaction { + string emoji = 1; + // Sum of the fees of every reaction with this emoji. + int64 fee_sats = 2; } message ListCoinNewsResponse { @@ -203,8 +219,9 @@ message CommentNewsRequest { string url = 3; string lang = 4; string reply_quote = 5; - // Fee options - exactly one should be set (0 = use Core's estimate) - uint64 fee_sat_per_vbyte = 6; + reserved 6; + reserved "fee_sat_per_vbyte"; + // Fee of the comment. It must be at least the fee of the root story (spec §7.1). uint64 fee_sats = 7; } @@ -212,6 +229,18 @@ message CommentNewsResponse { string txid = 1; } +message ReactNewsRequest { + // Hex-encoded 12-byte ItemID of the story or comment. + string parent_id = 1; + string emoji = 2; + // Fee of the reaction. It adds to the total of the emoji. + uint64 fee_sats = 3; +} + +message ReactNewsResponse { + string txid = 1; +} + message ListCommentsRequest { // Hex-encoded 12-byte ItemID whose reply thread to return. string item_id = 1; diff --git a/bitwindow/test/broadcast_news_topic_test.dart b/bitwindow/test/broadcast_news_topic_test.dart index cc041d6080..c12c7c755c 100644 --- a/bitwindow/test/broadcast_news_topic_test.dart +++ b/bitwindow/test/broadcast_news_topic_test.dart @@ -36,6 +36,7 @@ class _BroadcastAPI extends MockMiscAPI { bool nsfw = false, String topicName = '', int retentionDays = 0, + String emoji = '', }) async { estimated.add((headline: headline, body: body, url: url, subtype: subtype, nsfw: nsfw)); if (estimateError case final error?) { diff --git a/bitwindow/test/coinnews_article_panel_test.dart b/bitwindow/test/coinnews_article_panel_test.dart deleted file mode 100644 index a264131344..0000000000 --- a/bitwindow/test/coinnews_article_panel_test.dart +++ /dev/null @@ -1,170 +0,0 @@ -import 'package:bitwindow/widgets/coinnews.dart'; -import 'package:bitwindow/widgets/news_cost.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_it/get_it.dart'; -import 'package:sail_ui/sail_ui.dart'; - -import 'mocks/api_mock.dart'; -import 'test_utils.dart'; - -const _story = '0123456789abcdef01234567'; - -class _MiscAPI extends MockMiscAPI { - List comments = []; - - @override - Future listComments(String itemId) async => ListCommentsResponse(comments: comments); - - @override - Future estimateNewsFee( - NewsAction action, { - String body = '', - String headline = '', - String url = '', - int subtype = 0, - bool nsfw = false, - String topicName = '', - int retentionDays = 0, - }) async => NewsFeeEstimate(vsize: 263, feeSatPerVbyte: 21, feeSats: 5544); -} - -class _API extends MockAPI { - _API() : super(binaryType: BinaryType.BINARY_TYPE_BITWINDOWD); - - final _MiscAPI fakeMisc = _MiscAPI(); - - @override - _MiscAPI get misc => fakeMisc; -} - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - late _API rpc; - - setUp(() async { - await GetIt.I.reset(); - rpc = _API(); - GetIt.I.registerSingleton(rpc); - await registerTestDependencies(); - await loadBundledFonts(); - }); - - tearDown(() { - SailStyleValues.phoneLayoutOverride = null; - return GetIt.I.reset(); - }); - - Future openArticle(WidgetTester tester, {String headline = 'Headline'}) async { - await tester.pumpSailPage( - Builder( - builder: (context) => Center( - child: SailButton( - label: 'Open', - onPressed: () async => showCoinNewsArticle( - context, - CoinNews(headline: headline, content: 'Text', topic: 'a1a1a1a1', itemId: _story), - ), - ), - ), - ), - ); - await tester.tap(find.text('Open')); - await tester.pumpAndSettle(); - } - - testWidgets('a story opens as a 380 px panel at the right edge and × closes it', (tester) async { - await openArticle(tester); - - final panel = tester.getRect(find.byType(CoinNewsArticlePanel)); - expect(panel.width, 380); - expect(panel.right, 1200 - SailStyleValues.padding12); - expect(panel.height, 720 - 2 * SailStyleValues.padding12); - expect(find.text('Close'), findsNothing); - - await tester.tap(find.byType(SailIconBoxButton)); - await tester.pumpAndSettle(); - expect(find.byType(CoinNewsArticlePanel), findsNothing); - }); - - testWidgets('a phone opens the story as a sheet over the full width', (tester) async { - SailStyleValues.phoneLayoutOverride = true; - await openArticle(tester); - - expect(tester.getSize(find.byType(CoinNewsArticlePanel)).width, greaterThan(1190)); - }); - - testWidgets('the panel keeps the theme style of the app with the opposite brightness', (tester) async { - await openArticle(tester); - - final app = SailTheme.of(tester.element(find.text('Open'))); - final panel = SailTheme.of(tester.element(find.text('Headline'))); - expect(panel.style, app.style); - expect(panel.isLightMode(), !app.isLightMode()); - }); - - testWidgets('the panel wraps a long headline', (tester) async { - final headline = 'W' * 64; - await openArticle(tester, headline: headline); - - expect(tester.getSize(find.text(headline)).height, greaterThan(40)); - expect(tester.takeException(), isNull); - }); - - testWidgets('the panel shows all of a long comment', (tester) async { - final body = 'A comment that does not fit on one line ' * 5; - rpc.misc.comments = [Comment(itemId: 'c1', parentId: _story, author: '3f9ac21e7b00ffff', body: body)]; - await openArticle(tester); - - expect(tester.getSize(find.text(body)).height, greaterThan(3 * 13)); - }); - - testWidgets('a deep thread stays inside the panel', (tester) async { - rpc.misc.comments = [ - for (var i = 0; i < 30; i++) - Comment( - itemId: 'c$i', - parentId: i == 0 ? _story : 'c${i - 1}', - author: '3f9ac21e7b00ffff', - body: 'Reply $i', - ), - ]; - await openArticle(tester); - - expect(tester.takeException(), isNull); - final first = tester.getRect(find.text('Reply 0')); - expect(tester.getRect(find.text('Reply 1')).left, first.left + SailStyleValues.padding16); - final last = tester.getRect(find.text('Reply 29')); - expect(last.left, first.left + 5 * SailStyleValues.padding16); - expect(last.height, first.height, reason: 'the deepest reply does not wrap'); - }); - - testWidgets('the first comment notice shows the fee, × backs out and Comment accepts', (tester) async { - late BuildContext context; - await tester.pumpSailPage( - Builder( - builder: (c) { - context = c; - return const SizedBox(); - }, - ), - ); - - var answer = NewsCost.confirmFirstComment(context, body: 'Hello'); - await tester.pumpAndSettle(); - expect(find.text('≈ ${GetIt.I.get().formatSats(5544)}'), findsOneWidget); - expect(find.text('263 vB at 21.0 sat/vB'), findsOneWidget); - expect(tester.getSize(find.textContaining('Commenting writes')).height, greaterThan(2 * 13)); - expect(find.text('Cancel'), findsNothing); - await tester.tap(find.byType(SailIconBoxButton)); - await tester.pumpAndSettle(); - expect(await answer, isFalse); - - answer = NewsCost.confirmFirstComment(context, body: 'Hello'); - await tester.pumpAndSettle(); - await tester.tap(find.widgetWithText(SailButton, 'Comment')); - await tester.pumpAndSettle(); - expect(await answer, isTrue); - }); -} diff --git a/bitwindow/test/coinnews_article_topic_test.dart b/bitwindow/test/coinnews_article_topic_test.dart index bf05ba0578..1a6405b062 100644 --- a/bitwindow/test/coinnews_article_topic_test.dart +++ b/bitwindow/test/coinnews_article_topic_test.dart @@ -1,10 +1,7 @@ import 'package:bitwindow/providers/news_provider.dart'; -import 'package:bitwindow/widgets/coinnews.dart'; import 'package:fixnum/fixnum.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:get_it/get_it.dart'; -import 'package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart'; import 'package:sail_ui/sail_ui.dart'; import 'test_utils.dart'; @@ -12,30 +9,11 @@ import 'test_utils.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - final time = DateTime.utc(2026, 11, 16, 16, 32); final topics = [ Topic(id: Int64(1), topic: 'a1a1a1a1', name: 'US Weekly', confirmed: true), Topic(id: Int64(2), topic: 'b2b2b2b2', name: 'Japan Weekly'), ]; - CoinNews story(String topic) => - CoinNews(headline: 'Headline', topic: topic, createTime: Timestamp.fromDateTime(time)); - - Future pumpPanel(WidgetTester tester, String topic) async { - await tester.pumpSailPage( - SizedBox( - width: 1000, - height: 600, - child: CoinNewsArticlePanel(news: story(topic), onClose: () async {}), - ), - ); - await tester.pumpAndSettle(); - final provider = GetIt.I.get(); - provider.topics = topics; - provider.notifyListeners(); - await tester.pumpAndSettle(); - } - test('topicName returns the name of a known topic and null for an unknown topic', () async { await registerTestDependencies(); final provider = GetIt.I.get(); @@ -45,24 +23,4 @@ void main() { expect(provider.topicName('b2b2b2b2'), 'Japan Weekly'); expect(provider.topicName('ffffffff'), isNull); }); - - testWidgets('article panel shows the topic name and the date', (tester) async { - await pumpPanel(tester, 'a1a1a1a1'); - - expect(find.text('US Weekly · ${formatDate(time)}'), findsOneWidget); - expect(find.textContaining('a1a1a1a1'), findsNothing); - }); - - testWidgets('article panel shows a pending topic name without a pending mark', (tester) async { - await pumpPanel(tester, 'b2b2b2b2'); - - expect(find.text('Japan Weekly · ${formatDate(time)}'), findsOneWidget); - }); - - testWidgets('article panel shows only the date for an unknown topic', (tester) async { - await pumpPanel(tester, 'ffffffff'); - - expect(find.text(formatDate(time)), findsOneWidget); - expect(find.textContaining('ffffffff'), findsNothing); - }); } diff --git a/bitwindow/test/coinnews_chain_text_test.dart b/bitwindow/test/coinnews_chain_text_test.dart index a00d698920..8c645d278c 100644 --- a/bitwindow/test/coinnews_chain_text_test.dart +++ b/bitwindow/test/coinnews_chain_text_test.dart @@ -113,26 +113,6 @@ void main() { expect(menu.hitTestable(), findsOneWidget); }); - testWidgets('a picture in a story shows as a link and loads nothing', (tester) async { - await tester.pumpSailPage( - CoinNewsArticlePanel( - news: CoinNews( - headline: 'Story', - content: - 'Above\n\n![A chart](https://example.org/a.png)\n\n![](https://example.org/b.png)\n\n![Local](file:///a)', - topic: _longId, - ), - onClose: () async {}, - ), - ); - await tester.pumpAndSettle(); - - expect(find.byType(Image), findsNothing); - expect(find.text('A chart'), findsOneWidget); - expect(find.text('https://example.org/b.png'), findsOneWidget); - expect(find.text('Local'), findsOneWidget); - }); - test('a line reads the long name of a topic on the chain', () { final line = TopicLine.parse('7{$_longId}$_longName'); expect(line.name, _longName.trim()); diff --git a/bitwindow/test/coinnews_comments_test.dart b/bitwindow/test/coinnews_comments_test.dart deleted file mode 100644 index aa1a32672a..0000000000 --- a/bitwindow/test/coinnews_comments_test.dart +++ /dev/null @@ -1,285 +0,0 @@ -import 'dart:ui'; - -import 'package:bitwindow/providers/blockchain_provider.dart'; -import 'package:bitwindow/widgets/coinnews.dart'; -import 'package:fixnum/fixnum.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_it/get_it.dart'; -import 'package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart'; -import 'package:sail_ui/sail_ui.dart'; - -import 'mocks/api_mock.dart'; -import 'test_utils.dart'; - -const _story = '0123456789abcdef01234567'; - -class _MiscAPI extends MockMiscAPI { - List comments = []; - bool failList = false; - String indexerError = ''; - bool failPost = false; - bool failEstimate = false; - final List estimated = []; - - @override - Future listComments(String itemId) async { - if (failList) { - throw Exception('connection refused'); - } - return ListCommentsResponse(comments: comments, indexerError: indexerError); - } - - @override - Future commentNews( - String parentId, - String body, { - String? url, - String? lang, - String? replyQuote, - int? feeSatPerVbyte, - int? feeSats, - }) async { - if (failPost) { - throw BitwindowException('could not comment on news: the node does not answer'); - } - comments = [ - ...comments, - Comment( - itemId: 'mine', - parentId: parentId, - author: 'feedfeedfeedfeed', - body: body, - feeSats: Int64(700), - pending: true, - ), - ]; - return CommentNewsResponse(); - } - - @override - Future estimateNewsFee( - NewsAction action, { - String body = '', - String headline = '', - String url = '', - int subtype = 0, - bool nsfw = false, - String topicName = '', - int retentionDays = 0, - }) async { - estimated.add(body); - if (failEstimate) { - throw BitwindowException('could not estimate news fee: wallet is locked'); - } - return NewsFeeEstimate(vsize: 100 + body.length, feeSatPerVbyte: 1, feeSats: 100 + body.length); - } -} - -class _API extends MockAPI { - _API() : super(binaryType: BinaryType.BINARY_TYPE_BITWINDOWD); - - final _MiscAPI fakeMisc = _MiscAPI(); - - @override - _MiscAPI get misc => fakeMisc; -} - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - late _API rpc; - final time = DateTime.utc(2026, 11, 16, 16, 32); - - Comment mined(String id, String body, {String parent = _story, int fee = 1200}) => Comment( - itemId: id, - parentId: parent, - author: '3f9ac21e7b00ffff', - body: body, - feeSats: Int64(fee), - createTime: Timestamp.fromDateTime(time), - ); - - setUp(() async { - await GetIt.I.reset(); - rpc = _API(); - GetIt.I.registerSingleton(rpc); - await registerTestDependencies(); - await GetIt.I.get().setValue(CommentWarningSeenSetting(newValue: true)); - }); - - tearDown(() => GetIt.I.reset()); - - Future pumpPanel(WidgetTester tester) async { - await tester.pumpSailPage( - SizedBox( - width: 1000, - height: 600, - child: CoinNewsArticlePanel( - news: CoinNews(headline: 'Headline', topic: 'a1a1a1a1', itemId: _story), - onClose: () async {}, - ), - ), - ); - await tester.pumpAndSettle(); - } - - final commentButton = find.widgetWithText(SailButton, 'Comment').first; - - Future post(WidgetTester tester, String text) async { - await tester.enterText(find.byType(TextField), text); - await tester.tap(commentButton); - await tester.pumpAndSettle(); - } - - Future hoverComment(WidgetTester tester) async { - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - await mouse.addPointer(location: Offset.zero); - addTearDown(mouse.removePointer); - await mouse.moveTo(tester.getCenter(commentButton)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 600)); - await tester.pump(const Duration(milliseconds: 200)); - } - - testWidgets('a posted comment shows at once as pending', (tester) async { - await pumpPanel(tester); - expect(find.text('No comments yet. Be the first.'), findsOneWidget); - - await post(tester, 'My comment'); - - expect(find.text('Comments (1)'), findsOneWidget); - expect(find.text('My comment'), findsOneWidget); - expect(find.textContaining('feedfeedfe… · Pending · '), findsOneWidget); - expect(find.text('No comments yet. Be the first.'), findsNothing); - expect(find.text('Reply'), findsNothing, reason: 'a reply waits for the block of its parent'); - - rpc.misc.comments = [mined('mine', 'My comment')]; - GetIt.I.get().notifyListeners(); - await tester.pumpAndSettle(); - expect(find.text('Reply'), findsWidgets); - }); - - testWidgets('a comment shows its date and its fee', (tester) async { - rpc.misc.comments = [mined('c1', 'First'), mined('c2', 'No fee known', fee: 0)]; - await pumpPanel(tester); - - final fee = GetIt.I.get().formatSats(1200); - expect(find.text('3f9ac21e7b… · ${formatDate(time)} · $fee'), findsOneWidget); - expect(find.text('3f9ac21e7b… · ${formatDate(time)}'), findsOneWidget); - }); - - testWidgets('a new block or mempool transaction reads the thread again', (tester) async { - await pumpPanel(tester); - final blockchain = GetIt.I.get(); - - rpc.misc.comments = [mined('c1', 'From another node')]; - blockchain.notifyListeners(); - await tester.pumpAndSettle(); - expect(find.text('From another node'), findsOneWidget); - - rpc.misc.comments = [mined('c1', 'From another node'), mined('c2', 'From the mempool')]; - (blockchain.recentChanged as ChangeNotifier).notifyListeners(); - await tester.pumpAndSettle(); - expect(find.text('From the mempool'), findsOneWidget); - expect(find.text('Loading comments…'), findsNothing); - }); - - testWidgets('a failed post keeps the thread and the text, and shows the error', (tester) async { - rpc.misc.comments = [mined('c1', 'First')]; - await pumpPanel(tester); - rpc.misc.failPost = true; - - await post(tester, 'Does not go out'); - - expect(find.text('First'), findsOneWidget); - expect(find.text('Could not comment on news: the node does not answer'), findsOneWidget); - expect(find.textContaining('BitwindowException'), findsNothing); - expect(tester.widget(find.byType(TextField)).controller!.text, 'Does not go out'); - - rpc.misc.failPost = false; - await tester.tap(commentButton); - await tester.pumpAndSettle(); - expect(find.textContaining('the node does not answer'), findsNothing); - expect(find.text('Does not go out'), findsOneWidget); - }); - - testWidgets('a failed read keeps the comments of the last read', (tester) async { - rpc.misc.comments = [mined('c1', 'First')]; - await pumpPanel(tester); - - rpc.misc.failList = true; - GetIt.I.get().notifyListeners(); - await tester.pumpAndSettle(); - - expect(find.text('First'), findsOneWidget); - expect(find.textContaining('connection refused'), findsOneWidget); - }); - - testWidgets('a failed indexer read shows the reason over the local comments', (tester) async { - rpc.misc - ..comments = [Comment(itemId: 'c1', parentId: _story, author: 'a', body: 'Local comment')] - ..indexerError = 'read coin news indexer: connection refused'; - await pumpPanel(tester); - - expect(find.text('Local comment'), findsOneWidget); - expect( - find.text('Could not list comments: read coin news indexer: connection refused'), - findsOneWidget, - ); - }); - - testWidgets('the fee tooltip prices the text in the field', (tester) async { - await pumpPanel(tester); - await tester.enterText(find.byType(TextField), 'hello'); - await hoverComment(tester); - - expect(rpc.misc.estimated, ['hello']); - expect(find.textContaining('≈ 0.0000,0105 BTC'), findsOneWidget); - - await tester.enterText(find.byType(TextField), 'hello again'); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 600)); - await tester.pump(const Duration(milliseconds: 200)); - expect(rpc.misc.estimated, ['hello', 'hello again']); - expect(find.textContaining('≈ 0.0000,0111 BTC'), findsOneWidget); - }); - - testWidgets('the fee tooltip does not wait for an estimate that failed', (tester) async { - rpc.misc.failEstimate = true; - await pumpPanel(tester); - await tester.enterText(find.byType(TextField), 'hello'); - await hoverComment(tester); - - expect(rpc.misc.estimated, ['hello']); - expect(find.text('Checking the fee…'), findsNothing); - expect(find.text('Could not estimate news fee: wallet is locked'), findsOneWidget); - }); - - testWidgets('the first comment warning shows why the fee estimate failed', (tester) async { - await GetIt.I.get().setValue(CommentWarningSeenSetting(newValue: false)); - rpc.misc.failEstimate = true; - await pumpPanel(tester); - - await tester.enterText(find.byType(TextField), 'A comment'); - await tester.tap(commentButton); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - - expect(find.text('Commenting costs a fee'), findsOneWidget); - expect(find.text('Could not estimate news fee: wallet is locked'), findsOneWidget); - }); - - testWidgets('the first comment warning prices the comment text', (tester) async { - await GetIt.I.get().setValue(CommentWarningSeenSetting(newValue: false)); - await pumpPanel(tester); - - await tester.enterText(find.byType(TextField), 'A comment of 26 characters'); - await tester.tap(commentButton); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - - expect(rpc.misc.estimated, ['A comment of 26 characters']); - expect(find.textContaining('≈ 0.0000,0126 BTC'), findsOneWidget); - }); -} diff --git a/bitwindow/test/coinnews_pending_story_test.dart b/bitwindow/test/coinnews_pending_story_test.dart index bebd13638f..8295c67daa 100644 --- a/bitwindow/test/coinnews_pending_story_test.dart +++ b/bitwindow/test/coinnews_pending_story_test.dart @@ -67,12 +67,6 @@ void main() { tearDown(() => GetIt.I.reset()); - void readNews(List news) { - final provider = GetIt.I.get(); - provider.news = news; - provider.notifyListeners(); - } - test('storyTime gives Pending for a story in the mempool and the time for a story in a block', () { expect(storyTime(pending, formatDate), 'Pending'); expect(storyTime(confirmed, formatDate), formatDate(mined)); @@ -91,48 +85,4 @@ void main() { expect(find.text('Pending'), findsOneWidget); expect(find.text(formatDate(seen, long: false)), findsNothing); }); - - testWidgets('the article panel shows the comments after the block of an open pending story', (tester) async { - await tester.pumpSailPage( - SizedBox( - width: 1000, - height: 600, - child: CoinNewsArticlePanel(news: pending, onClose: () async {}), - ), - ); - await tester.pumpAndSettle(); - - expect(find.text('US Weekly · Pending'), findsOneWidget); - expect(find.text('Comments open when the story is in a block.'), findsOneWidget); - expect(find.widgetWithText(SailButton, 'Comment'), findsNothing); - expect(rpc.misc.reads, isEmpty); - - readNews([confirmed]); - await tester.pumpAndSettle(); - - expect(find.text('US Weekly · ${formatDate(mined)}'), findsOneWidget); - expect(find.text('No comments yet. Be the first.'), findsOneWidget); - expect(find.widgetWithText(SailButton, 'Comment'), findsWidgets); - expect(rpc.misc.reads, [_itemId]); - }); - - testWidgets('the article panel closes the comments when a reorg sends the story back to the mempool', (tester) async { - readNews([confirmed]); - await tester.pumpSailPage( - SizedBox( - width: 1000, - height: 600, - child: CoinNewsArticlePanel(news: confirmed, onClose: () async {}), - ), - ); - await tester.pumpAndSettle(); - expect(find.widgetWithText(SailButton, 'Comment'), findsWidgets); - - readNews([pending]); - await tester.pumpAndSettle(); - - expect(find.text('US Weekly · Pending'), findsOneWidget); - expect(find.text('Comments open when the story is in a block.'), findsOneWidget); - expect(find.widgetWithText(SailButton, 'Comment'), findsNothing); - }); } diff --git a/bitwindow/test/coinnews_story_meta_test.dart b/bitwindow/test/coinnews_story_meta_test.dart index 780f10617f..04ee94da62 100644 --- a/bitwindow/test/coinnews_story_meta_test.dart +++ b/bitwindow/test/coinnews_story_meta_test.dart @@ -1,21 +1,14 @@ -import 'dart:io'; - -import 'package:bitwindow/providers/news_provider.dart'; import 'package:bitwindow/widgets/coinnews.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:get_it/get_it.dart'; import 'package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart'; import 'package:sail_ui/sail_ui.dart'; -import 'test_utils.dart'; - void main() { TestWidgetsFlutterBinding.ensureInitialized(); tearDown(() => GetIt.I.reset()); final time = DateTime.utc(2026, 11, 16, 16, 32); - final topics = [Topic(topic: 'a1a1a1a1', name: 'US Weekly', confirmed: true, retentionDays: 30)]; CoinNews story({ String headline = 'Headline', @@ -33,38 +26,10 @@ void main() { createTime: Timestamp.fromDateTime(time), ); - Future> pumpPanel(WidgetTester tester, CoinNews news) async { - final opened = []; - openUrlProcessRunner = (executable, arguments) async { - opened.addAll(arguments); - return ProcessResult(0, 0, '', ''); - }; - addTearDown(() => openUrlProcessRunner = Process.run); - await tester.pumpSailPage( - SizedBox( - width: 1000, - height: 600, - child: CoinNewsArticlePanel(news: news, onClose: () async {}), - ), - ); - await tester.pumpAndSettle(); - final provider = GetIt.I.get(); - provider.topics = topics; - provider.notifyListeners(); - await tester.pumpAndSettle(); - return opened; - } - test('the story line names each kind but a link, and marks NSFW', () { expect(storyMeta(story(), topicName: 'US Weekly', date: 'today'), 'US Weekly · today'); expect(storyMeta(story(subtype: 2), topicName: 'US Weekly', date: 'today'), 'US Weekly · Ask · today'); expect(storyMeta(story(subtype: 5, nsfw: true), topicName: null, date: 'today'), 'Job · NSFW · today'); expect(storyMeta(story(subtype: 99), topicName: null, date: 'today'), 'today'); }); - - testWidgets('the article shows the kind and the NSFW mark of the story', (tester) async { - await pumpPanel(tester, story(subtype: 2, nsfw: true)); - - expect(find.text('US Weekly · Ask · NSFW · ${formatDate(time)}'), findsOneWidget); - }); } diff --git a/bitwindow/test/coinnews_web_link_test.dart b/bitwindow/test/coinnews_web_link_test.dart index 1e486ba659..a382c33eef 100644 --- a/bitwindow/test/coinnews_web_link_test.dart +++ b/bitwindow/test/coinnews_web_link_test.dart @@ -1,61 +1,7 @@ -import 'dart:io'; - -import 'package:bitwindow/providers/news_provider.dart'; import 'package:bitwindow/utils/web_link.dart'; -import 'package:bitwindow/widgets/coinnews.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:get_it/get_it.dart'; -import 'package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart'; -import 'package:sail_ui/sail_ui.dart'; - -import 'test_utils.dart'; void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - tearDown(() => GetIt.I.reset()); - - final time = DateTime.utc(2026, 11, 16, 16, 32); - final topics = [Topic(topic: 'a1a1a1a1', name: 'US Weekly', confirmed: true, retentionDays: 30)]; - - CoinNews story({ - String headline = 'Headline', - int subtype = 0, - bool nsfw = false, - String url = '', - String content = '', - }) => CoinNews( - headline: headline, - topic: 'a1a1a1a1', - subtype: subtype, - nsfw: nsfw, - url: url, - content: content, - createTime: Timestamp.fromDateTime(time), - ); - - Future> pumpPanel(WidgetTester tester, CoinNews news) async { - final opened = []; - openUrlProcessRunner = (executable, arguments) async { - opened.addAll(arguments); - return ProcessResult(0, 0, '', ''); - }; - addTearDown(() => openUrlProcessRunner = Process.run); - await tester.pumpSailPage( - SizedBox( - width: 1000, - height: 600, - child: CoinNewsArticlePanel(news: news, onClose: () async {}), - ), - ); - await tester.pumpAndSettle(); - final provider = GetIt.I.get(); - provider.topics = topics; - provider.notifyListeners(); - await tester.pumpAndSettle(); - return opened; - } - test('only an http or https address is a web link', () { expect(webLink('https://example.com/a?b=c'), Uri.parse('https://example.com/a?b=c')); expect(webLink(' http://example.com '), Uri.parse('http://example.com')); @@ -65,37 +11,4 @@ void main() { expect(webLink('not a url %%'), isNull); expect(webLink(''), isNull); }); - - testWidgets('the article opens a web link', (tester) async { - final opened = await pumpPanel(tester, story(url: 'https://example.com/job')); - - await tester.tap(find.text('https://example.com/job')); - await tester.pumpAndSettle(); - - expect(opened, ['https://example.com/job']); - }); - - testWidgets('the article opens no link that is not a web link', (tester) async { - final opened = await pumpPanel( - tester, - story(url: 'file:///System/Applications/Calculator.app', content: '[read more](file:///etc/hosts)'), - ); - - await tester.tap(find.text('file:///System/Applications/Calculator.app')); - await tester.tap(find.text('read more')); - await tester.pumpAndSettle(); - - expect(tester.takeException(), isNull); - expect(opened, isEmpty); - }); - - testWidgets('the article shows a link with no scheme and stays silent on a tap', (tester) async { - final opened = await pumpPanel(tester, story(url: 'example.com/no-scheme')); - - await tester.tap(find.text('example.com/no-scheme')); - await tester.pumpAndSettle(); - - expect(tester.takeException(), isNull); - expect(opened, isEmpty); - }); } diff --git a/bitwindow/test/coinnews_window_test.dart b/bitwindow/test/coinnews_window_test.dart new file mode 100644 index 0000000000..92e921dcdc --- /dev/null +++ b/bitwindow/test/coinnews_window_test.dart @@ -0,0 +1,342 @@ +import 'dart:io'; + +import 'package:bitwindow/providers/blockchain_provider.dart'; +import 'package:bitwindow/providers/news_provider.dart'; +import 'package:bitwindow/widgets/coinnews_window.dart'; +import 'package:fixnum/fixnum.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:get_it/get_it.dart'; +import 'package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart'; +import 'package:sail_ui/sail_ui.dart'; + +import 'mocks/api_mock.dart'; +import 'test_utils.dart'; + +const _itemId = '0123456789abcdef01234567'; +const _txid = 'aa00000000000000000000000000000000000000000000000000000000000001'; + +class _MiscAPI extends MockMiscAPI { + List news = []; + List topics = []; + List comments = []; + String indexerError = ''; + bool failList = false; + bool failPost = false; + final posted = <({String parent, String body, int fee})>[]; + final reacted = <({String parent, String emoji, int fee})>[]; + int reads = 0; + + @override + Future listCoinNews() async => ListCoinNewsResponse(coinNews: news); + + @override + Future> listTopics() async => topics; + + @override + Future listComments(String itemId) async { + reads++; + if (failList) { + throw Exception('connection refused'); + } + return ListCommentsResponse(comments: comments, indexerError: indexerError); + } + + @override + Future commentNews( + String parentId, + String body, { + required int feeSats, + String? url, + String? lang, + String? replyQuote, + }) async { + if (failPost) { + throw BitwindowException('could not comment on news: the node does not answer'); + } + posted.add((parent: parentId, body: body, fee: feeSats)); + comments = [ + ...comments, + Comment(itemId: 'mine', parentId: parentId, body: body, feeSats: Int64(feeSats), pending: true), + ]; + return CommentNewsResponse(); + } + + @override + Future reactNews(String parentId, String emoji, {required int feeSats}) async { + reacted.add((parent: parentId, emoji: emoji, fee: feeSats)); + return ReactNewsResponse(); + } + + @override + Future estimateNewsFee( + NewsAction action, { + String body = '', + String headline = '', + String url = '', + int subtype = 0, + bool nsfw = false, + String topicName = '', + int retentionDays = 0, + String emoji = '', + }) async => NewsFeeEstimate(vsize: 141, feeSatPerVbyte: 1, feeSats: 141); +} + +class _API extends MockAPI { + _API() : super(binaryType: BinaryType.BINARY_TYPE_BITWINDOWD); + + final _MiscAPI fakeMisc = _MiscAPI(); + + @override + _MiscAPI get misc => fakeMisc; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _API rpc; + final time = DateTime.utc(2026, 11, 30, 18, 2); + + CoinNews story({ + String headline = 'Drivechain upgrade successfully completed', + String content = 'Deposits work.', + String url = '', + int fee = 12400, + String itemId = _itemId, + int subtype = 0, + bool nsfw = false, + List reactions = const [], + }) => CoinNews( + headline: headline, + content: content, + url: url, + topic: 'a1a1a1a1', + feeSats: Int64(fee), + itemId: itemId, + txid: _txid, + subtype: subtype, + nsfw: nsfw, + maxCommentChars: headline.runes.length + content.runes.length, + reactions: reactions, + createTime: Timestamp.fromDateTime(time), + ); + + setUp(() async { + await GetIt.I.reset(); + rpc = _API(); + GetIt.I.registerSingleton(rpc); + await registerTestDependencies(); + }); + + tearDown(() => GetIt.I.reset()); + + void readNews(List news) { + final topics = [Topic(topic: 'a1a1a1a1', name: 'US Weekly', confirmed: true, retentionDays: 7)]; + rpc.fakeMisc + ..news = news + ..topics = topics; + final provider = GetIt.I.get(); + provider.topics = topics; + provider.news = news; + provider.notifyListeners(); + } + + Future> pumpWindow(WidgetTester tester, List news, {String? open}) async { + final opened = []; + openUrlProcessRunner = (executable, arguments) async { + opened.addAll(arguments); + return ProcessResult(0, 0, '', ''); + }; + addTearDown(() => openUrlProcessRunner = Process.run); + await tester.pumpSailPage(SizedBox(width: 900, height: 660, child: CoinNewsWindow(story: open))); + readNews(news); + await tester.pumpAndSettle(); + return opened; + } + + final commentButton = find.widgetWithText(SailButton, 'Comment'); + + testWidgets('the feed lists the stories of the topic highest fee first, and a read story turns grey', (tester) async { + await pumpWindow(tester, [ + story(headline: 'Dear', fee: 12400, itemId: 'aa'), + story(headline: 'Cheap', fee: 1000, itemId: 'bb'), + ]); + + expect(find.text('2 stories'), findsOneWidget); + expect(find.text('Last 7 days'), findsOneWidget); + expect(tester.getTopLeft(find.text('Dear')).dy, lessThan(tester.getTopLeft(find.text('Cheap')).dy)); + expect(tester.widget(find.text('Dear')).style!.color, const Color(0xff0000ee)); + + await tester.tap(find.text('Dear')); + await tester.pumpAndSettle(); + expect(find.text('Comments (0)'), findsOneWidget); + await tester.tap(find.text('< Back')); + await tester.pumpAndSettle(); + + expect(tester.widget(find.text('Dear')).style!.color, const Color(0xff808080)); + expect(tester.widget(find.text('Cheap')).style!.color, const Color(0xff0000ee)); + expect((await GetIt.I.get().getValue(ReadStoriesSetting())).value, ['aa']); + }); + + testWidgets('the story shows the fee, the kind, the NSFW mark and the topic', (tester) async { + await pumpWindow(tester, [story(subtype: 2, nsfw: true)], open: _itemId); + + expect(find.textContaining('US Weekly · Ask · NSFW'), findsOneWidget); + expect(find.textContaining('12'), findsWidgets); + expect(find.text('Deposits work.'), findsOneWidget); + }); + + testWidgets('comments sort by fee, and a posted comment shows at once as pending', (tester) async { + rpc.fakeMisc.comments = [ + Comment(itemId: 'c1', parentId: _itemId, body: 'Same here.', feeSats: Int64(12400)), + Comment(itemId: 'c2', parentId: _itemId, body: 'Withdrawals next.', feeSats: Int64(20000)), + ]; + await pumpWindow(tester, [story()], open: _itemId); + + expect(find.text('Comments (2)'), findsOneWidget); + expect( + tester.getTopLeft(find.text('Withdrawals next.')).dy, + lessThan(tester.getTopLeft(find.text('Same here.')).dy), + ); + + await tester.enterText(find.byType(TextField).first, 'Show the hash.'); + await tester.pumpAndSettle(); + await tester.tap(commentButton); + await tester.pumpAndSettle(); + + expect(rpc.fakeMisc.posted.single, (parent: _itemId, body: 'Show the hash.', fee: 12400)); + expect(find.text('Show the hash.'), findsOneWidget); + expect(find.text('Pending'), findsOneWidget); + }); + + testWidgets('a fee below the story fee or a text longer than the story keeps the comment back', (tester) async { + await pumpWindow(tester, [story(headline: 'Short', content: '', fee: 1000)], open: _itemId); + final fee = find.byType(TextField).at(1); + + await tester.enterText(find.byType(TextField).first, 'ok'); + await tester.enterText(fee, '999'); + await tester.pumpAndSettle(); + expect(find.textContaining('The fee must be'), findsOneWidget); + expect(tester.widget(commentButton).disabled, isTrue); + + await tester.enterText(fee, '1000'); + await tester.enterText(find.byType(TextField).first, 'Too long'); + await tester.pumpAndSettle(); + expect(find.text('The comment is longer than the story.'), findsOneWidget); + expect(find.text('8 / 5'), findsOneWidget); + expect(tester.widget(commentButton).disabled, isTrue); + + await tester.enterText(find.byType(TextField).first, 'Fine.'); + await tester.pumpAndSettle(); + expect(find.textContaining('The '), findsNothing); + expect(tester.widget(commentButton).disabled, isFalse); + }); + + testWidgets('a failed post keeps the text and shows the error', (tester) async { + rpc.fakeMisc.failPost = true; + await pumpWindow(tester, [story()], open: _itemId); + + await tester.enterText(find.byType(TextField).first, 'Show the hash.'); + await tester.pumpAndSettle(); + await tester.tap(commentButton); + await tester.pumpAndSettle(); + + expect(find.textContaining('the node does not answer'), findsOneWidget); + expect(find.text('Show the hash.'), findsOneWidget); + }); + + testWidgets('a new block reads the comments again, and a failed read keeps the last comments', (tester) async { + rpc.fakeMisc.comments = [Comment(itemId: 'c1', parentId: _itemId, body: 'First.', feeSats: Int64(12400))]; + await pumpWindow(tester, [story()], open: _itemId); + final reads = rpc.fakeMisc.reads; + + rpc.fakeMisc.failList = true; + GetIt.I.get().notifyListeners(); + await tester.pumpAndSettle(); + + expect(rpc.fakeMisc.reads, reads + 1); + expect(find.text('First.'), findsOneWidget); + expect(find.textContaining('connection refused'), findsOneWidget); + }); + + testWidgets('a reaction adds its fee to the total of the emoji', (tester) async { + await pumpWindow( + tester, + [ + story( + reactions: [ + Reaction(emoji: '👎', feeSats: Int64(617)), + Reaction(emoji: '👍', feeSats: Int64(3513)), + ], + ), + ], + open: _itemId, + ); + + await tester.tap(find.textContaining('👎')); + await tester.pumpAndSettle(); + expect(find.text('Add a reaction'), findsOneWidget); + + await tester.enterText(find.byType(TextField).last, '8000'); + await tester.pumpAndSettle(); + expect(find.textContaining('→'), findsOneWidget); + + await tester.tap(find.widgetWithText(SailButton, 'Send')); + await tester.pumpAndSettle(); + + expect(rpc.fakeMisc.reacted.single, (parent: _itemId, emoji: '👎', fee: 8000)); + expect(find.text('Add a reaction'), findsNothing); + }); + + testWidgets('a story link opens after the warning, and the warning can stay off', (tester) async { + final opened = await pumpWindow(tester, [story(url: 'https://google.com.login.evil.ru/doc')], open: _itemId); + + await tester.tap(find.text('https://google.com.login.evil.ru/doc')); + await tester.pumpAndSettle(); + expect(find.text('Open link?'), findsOneWidget); + await tester.tap(find.widgetWithText(SailButton, 'Cancel')); + await tester.pumpAndSettle(); + expect(opened, isEmpty); + + await tester.tap(find.text('https://google.com.login.evil.ru/doc')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Do not warn me again')); + await tester.tap(find.widgetWithText(SailButton, 'Open link')); + await tester.pumpAndSettle(); + expect(opened, ['https://google.com.login.evil.ru/doc']); + + await tester.tap(find.text('https://google.com.login.evil.ru/doc').first); + await tester.pumpAndSettle(); + expect(find.text('Open link?'), findsNothing); + expect(opened, ['https://google.com.login.evil.ru/doc', 'https://google.com.login.evil.ru/doc']); + }); + + testWidgets('a link that is not a web address shows as text and opens nothing', (tester) async { + final opened = await pumpWindow( + tester, + [story(url: 'file:///etc/hosts', content: '![x](https://example.com/a.png) [read](file:///etc/hosts)')], + open: _itemId, + ); + + await tester.tap(find.text('file:///etc/hosts')); + await tester.pumpAndSettle(); + + expect(find.text('Open link?'), findsNothing); + expect(find.text('![x](https://example.com/a.png) [read](file:///etc/hosts)'), findsOneWidget); + expect(opened, isEmpty); + }); + + testWidgets('a pending story opens its comments after its block', (tester) async { + final pending = story(itemId: '')..pending = true; + await pumpWindow(tester, [pending], open: '$_txid:0'); + + expect(find.text('Comments open when the story is in a block.'), findsOneWidget); + expect(commentButton, findsNothing); + + readNews([story()]); + await tester.pumpAndSettle(); + + expect(find.text('Comments open when the story is in a block.'), findsNothing); + expect(commentButton, findsOneWidget); + }); +} diff --git a/bitwindow/test/mocks/api_mock.dart b/bitwindow/test/mocks/api_mock.dart index f7504d5a0f..76e10df7e5 100644 --- a/bitwindow/test/mocks/api_mock.dart +++ b/bitwindow/test/mocks/api_mock.dart @@ -464,6 +464,7 @@ class MockMiscAPI implements MiscAPI { bool nsfw = false, String topicName = '', int retentionDays = 0, + String emoji = '', }) async { return NewsFeeEstimate(vsize: 152, feeSatPerVbyte: 1, feeSats: 152); } @@ -492,11 +493,10 @@ class MockMiscAPI implements MiscAPI { Future commentNews( String parentId, String body, { + required int feeSats, String? url, String? lang, String? replyQuote, - int? feeSatPerVbyte, - int? feeSats, }) async { return CommentNewsResponse(); } @@ -506,6 +506,11 @@ class MockMiscAPI implements MiscAPI { return ListCommentsResponse(); } + @override + Future reactNews(String parentId, String emoji, {required int feeSats}) async { + return ReactNewsResponse(); + } + @override Future createTopic(String topic, String name, {int retentionDays = 7}) async { return CreateTopicResponse(); diff --git a/bitwindow/test/news_subscriptions_test.dart b/bitwindow/test/news_subscriptions_test.dart index 69e3b24a9d..e1719bc41e 100644 --- a/bitwindow/test/news_subscriptions_test.dart +++ b/bitwindow/test/news_subscriptions_test.dart @@ -29,6 +29,7 @@ class RecordingMisc extends MockMiscAPI { bool nsfw = false, String topicName = '', int retentionDays = 0, + String emoji = '', }) async { expect(action, NewsAction.NEWS_ACTION_TOPIC); priced.add((topicName, retentionDays)); diff --git a/coinnews/codec/codec_test.go b/coinnews/codec/codec_test.go index baaa44ee69..f489d95123 100644 --- a/coinnews/codec/codec_test.go +++ b/coinnews/codec/codec_test.go @@ -220,3 +220,42 @@ func TestContinuationChunkBound(t *testing.T) { assert.Equal(t, c.Seq, got.Seq) assert.Equal(t, c.Chunk, got.Chunk) } + +// TestVector_Reaction matches the worked example in the spec's "Test Vectors" section. +func TestVector_Reaction(t *testing.T) { + r := Reaction{Parent: ItemID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, Emoji: "👍"} + got, err := EncodeReaction(r) + require.NoError(t, err) + assert.Equal(t, "434e07"+"0102030405060708090a0b0c"+"04"+"f09f918d", hex.EncodeToString(got)) + + tag, msg, err := DecodeMessage(got) + require.NoError(t, err) + assert.Equal(t, TypeReaction, tag) + assert.Equal(t, r, *msg.(*Reaction)) +} + +func TestReactionRejectsBadEmoji(t *testing.T) { + parent := ItemID{1} + for name, emoji := range map[string]string{ + "empty": "", + "too long": string(bytes.Repeat([]byte("a"), EmojiMaxLen+1)), + "not utf-8": "\xff", + } { + t.Run(name, func(t *testing.T) { + _, err := EncodeReaction(Reaction{Parent: parent, Emoji: emoji}) + require.Error(t, err) + + payload := append([]byte{'C', 'N', byte(TypeReaction)}, parent[:]...) + payload = append(payload, byte(len(emoji))) + payload = append(payload, emoji...) + _, _, err = DecodeMessage(payload) + require.Error(t, err) + }) + } + t.Run("trailing bytes", func(t *testing.T) { + payload := append([]byte{'C', 'N', byte(TypeReaction)}, parent[:]...) + payload = append(payload, 1, 'x', 'y') + _, _, err := DecodeMessage(payload) + require.Error(t, err) + }) +} diff --git a/coinnews/codec/constants.go b/coinnews/codec/constants.go index e3f078baaf..5188b2d3a9 100644 --- a/coinnews/codec/constants.go +++ b/coinnews/codec/constants.go @@ -13,6 +13,7 @@ const ( TypeStory TypeTag = 0x02 TypeComment TypeTag = 0x03 TypeContinuation TypeTag = 0x06 + TypeReaction TypeTag = 0x07 ) // Sizes used across the wire format. Constants rather than literals so @@ -35,6 +36,8 @@ const ( // forbidding longer ones (long headlines just pay the 3-byte // varint, same as long bodies). HeadlineMaxLen = 252 + // EmojiMaxLen caps a Reaction's emoji at 32 bytes. + EmojiMaxLen = 32 ) // TLVTag values defined in spec §10. Tags 0x80–0xef are reserved for the diff --git a/coinnews/codec/decode.go b/coinnews/codec/decode.go index 55cadb4eeb..8abbb236e1 100644 --- a/coinnews/codec/decode.go +++ b/coinnews/codec/decode.go @@ -3,6 +3,7 @@ package coinnews import ( "errors" "fmt" + "unicode/utf8" ) // ErrNotCoinNews indicates the payload's leading bytes don't match the @@ -19,7 +20,7 @@ var ErrUnknownTypeTag = errors.New("coinnews: unknown type tag") // DecodeMessage classifies the payload and returns one of: // -// *TopicCreation, *Story, *Comment, *Continuation +// *TopicCreation, *Story, *Comment, *Continuation, *Reaction // // plus the TypeTag for switch-friendly dispatch. Returns ErrNotCoinNews // for non-CoinNews traffic; any other error means the bytes claimed to @@ -47,6 +48,9 @@ func DecodeMessage(payload []byte) (TypeTag, any, error) { case TypeContinuation: c, err := decodeContinuation(body) return tag, c, err + case TypeReaction: + r, err := decodeReaction(body) + return tag, r, err default: // Unknown TypeTag: the magic matched, so the publisher // intended this as a CoinNews message, but we don't know how @@ -155,3 +159,37 @@ func decodeContinuation(b []byte) (*Continuation, error) { c.Chunk = append([]byte{}, b[ItemIDLen+1:]...) return &c, nil } + +func decodeReaction(b []byte) (*Reaction, error) { + if len(b) < ItemIDLen+1 { + return nil, fmt.Errorf("coinnews: reaction truncated") + } + var r Reaction + copy(r.Parent[:], b[:ItemIDLen]) + rest := b[ItemIDLen:] + n, consumed, err := decodeCompactSize(rest) + if err != nil { + return nil, fmt.Errorf("coinnews: emoji length: %w", err) + } + rest = rest[consumed:] + if uint64(len(rest)) != n { + return nil, fmt.Errorf("coinnews: emoji is %d bytes, want %d", len(rest), n) + } + r.Emoji = string(rest) + if err := checkEmoji(r.Emoji); err != nil { + return nil, err + } + return &r, nil +} + +func checkEmoji(e string) error { + switch { + case e == "": + return fmt.Errorf("coinnews: empty emoji") + case len(e) > EmojiMaxLen: + return fmt.Errorf("coinnews: emoji is %d bytes, max %d", len(e), EmojiMaxLen) + case !utf8.ValidString(e): + return fmt.Errorf("coinnews: emoji is not valid UTF-8") + } + return nil +} diff --git a/coinnews/codec/encode.go b/coinnews/codec/encode.go index 8d21530644..d20c1a78e6 100644 --- a/coinnews/codec/encode.go +++ b/coinnews/codec/encode.go @@ -83,3 +83,21 @@ func EncodeContinuation(c Continuation) ([]byte, error) { buf.Write(c.Chunk) return buf.Bytes(), nil } + +// EncodeReaction (spec §8): +// +// "CN" ‖ 0x07 ‖ parent_id(12) ‖ emoji(varint+UTF-8) +func EncodeReaction(r Reaction) ([]byte, error) { + if err := checkEmoji(r.Emoji); err != nil { + return nil, err + } + var buf bytes.Buffer + buf.Write(Magic[:]) + buf.WriteByte(byte(TypeReaction)) + buf.Write(r.Parent[:]) + if err := encodeCompactSize(&buf, uint64(len(r.Emoji))); err != nil { + return nil, err + } + buf.WriteString(r.Emoji) + return buf.Bytes(), nil +} diff --git a/coinnews/codec/message.go b/coinnews/codec/message.go index 6a4a1314d3..b87e2a94df 100644 --- a/coinnews/codec/message.go +++ b/coinnews/codec/message.go @@ -40,3 +40,9 @@ type Continuation struct { Seq byte Chunk []byte } + +// Reaction adds the fee of its transaction to one emoji of an Item (spec §8). +type Reaction struct { + Parent ItemID + Emoji string +} diff --git a/coinnews/codec/rules.go b/coinnews/codec/rules.go new file mode 100644 index 0000000000..af80dc2387 --- /dev/null +++ b/coinnews/codec/rules.go @@ -0,0 +1,41 @@ +package coinnews + +import ( + "errors" + "unicode/utf8" +) + +var ( + // ErrCommentFeeTooLow identifies a Comment that pays less than its root Story. + ErrCommentFeeTooLow = errors.New("coinnews: comment fee is lower than the story fee") + // ErrCommentTooLong identifies a Comment with more characters than its root Story. + ErrCommentTooLong = errors.New("coinnews: comment is longer than the story") +) + +// StoryRules is what spec §7.1 reads from the root Story of a Comment. +type StoryRules struct { + FeeSats int64 + Headline string + Body string +} + +// MaxCommentLen is the most characters a Comment on this Story can hold. +func (s StoryRules) MaxCommentLen() int { + return TextLen(s.Headline) + TextLen(s.Body) +} + +// CheckComment applies spec §7.1. Body is the Comment's own body TLV. +func CheckComment(story StoryRules, commentFeeSats int64, body string) error { + if commentFeeSats < story.FeeSats { + return ErrCommentFeeTooLow + } + if TextLen(body) > story.MaxCommentLen() { + return ErrCommentTooLong + } + return nil +} + +// TextLen counts the characters of a text field, as Unicode code points. +func TextLen(s string) int { + return utf8.RuneCountInString(Text(s)) +} diff --git a/coinnews/codec/rules_test.go b/coinnews/codec/rules_test.go new file mode 100644 index 0000000000..c3e5483823 --- /dev/null +++ b/coinnews/codec/rules_test.go @@ -0,0 +1,30 @@ +package coinnews_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + coinnews "github.com/LayerTwo-Labs/sidesail/coinnews/codec" +) + +func TestCheckComment(t *testing.T) { + story := coinnews.StoryRules{FeeSats: 1000, Headline: "Héllo", Body: "wörld"} + for _, tc := range []struct { + name string + fee int64 + body string + want error + }{ + {"same fee, same length", 1000, "0123456789", nil}, + {"higher fee, empty", 5000, "", nil}, + {"lower fee", 999, "ok", coinnews.ErrCommentFeeTooLow}, + {"one character too long", 1000, "01234567890", coinnews.ErrCommentTooLong}, + {"emoji count as one character", 1000, "👍👍👍👍👍👍👍👍👍👍", nil}, + {"invalid bytes count as one character each", 1000, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", nil}, + } { + t.Run(tc.name, func(t *testing.T) { + require.ErrorIs(t, coinnews.CheckComment(story, tc.fee, tc.body), tc.want) + }) + } +} diff --git a/coinnews/gen/coinnews/v1/coinnews_pb.d.ts b/coinnews/gen/coinnews/v1/coinnews_pb.d.ts index 8f9d603692..1f9206aff0 100644 --- a/coinnews/gen/coinnews/v1/coinnews_pb.d.ts +++ b/coinnews/gen/coinnews/v1/coinnews_pb.d.ts @@ -93,6 +93,13 @@ export declare type Item = Message<"coinnews.v1.Item"> & { * @generated from field: int64 fee_sats = 19; */ feeSats: bigint; + + /** + * Reactions to the item, highest total first. + * + * @generated from field: repeated coinnews.v1.Reaction reactions = 20; + */ + reactions: Reaction[]; }; /** @@ -177,6 +184,13 @@ export declare type ItemJson = { * @generated from field: int64 fee_sats = 19; */ feeSats?: string; + + /** + * Reactions to the item, highest total first. + * + * @generated from field: repeated coinnews.v1.Reaction reactions = 20; + */ + reactions?: ReactionJson[]; }; /** @@ -252,6 +266,13 @@ export declare type Comment = Message<"coinnews.v1.Comment"> & { * @generated from field: int64 fee_sats = 14; */ feeSats: bigint; + + /** + * Reactions to the comment, highest total first. + * + * @generated from field: repeated coinnews.v1.Reaction reactions = 15; + */ + reactions: Reaction[]; }; /** @@ -321,6 +342,13 @@ export declare type CommentJson = { * @generated from field: int64 fee_sats = 14; */ feeSats?: string; + + /** + * Reactions to the comment, highest total first. + * + * @generated from field: repeated coinnews.v1.Reaction reactions = 15; + */ + reactions?: ReactionJson[]; }; /** @@ -329,6 +357,50 @@ export declare type CommentJson = { */ export declare const CommentSchema: GenMessage; +/** + * The fee total of one emoji on an item. + * + * @generated from message coinnews.v1.Reaction + */ +export declare type Reaction = Message<"coinnews.v1.Reaction"> & { + /** + * @generated from field: string emoji = 1; + */ + emoji: string; + + /** + * Sum of the fees of every reaction with this emoji, in sats. + * + * @generated from field: int64 fee_sats = 2; + */ + feeSats: bigint; +}; + +/** + * The fee total of one emoji on an item. + * + * @generated from message coinnews.v1.Reaction + */ +export declare type ReactionJson = { + /** + * @generated from field: string emoji = 1; + */ + emoji?: string; + + /** + * Sum of the fees of every reaction with this emoji, in sats. + * + * @generated from field: int64 fee_sats = 2; + */ + feeSats?: string; +}; + +/** + * Describes the message coinnews.v1.Reaction. + * Use `create(ReactionSchema)` to create a new message. + */ +export declare const ReactionSchema: GenMessage; + /** * @generated from message coinnews.v1.Topic */ diff --git a/coinnews/gen/coinnews/v1/coinnews_pb.js b/coinnews/gen/coinnews/v1/coinnews_pb.js index b232f5f73c..401d835c03 100644 --- a/coinnews/gen/coinnews/v1/coinnews_pb.js +++ b/coinnews/gen/coinnews/v1/coinnews_pb.js @@ -9,7 +9,7 @@ import { file_google_protobuf_empty, file_google_protobuf_timestamp } from "@buf * Describes the file coinnews/v1/coinnews.proto. */ export const file_coinnews_v1_coinnews = /*@__PURE__*/ - fileDesc("Chpjb2lubmV3cy92MS9jb2lubmV3cy5wcm90bxILY29pbm5ld3MudjEi/AIKBEl0ZW0SEwoLaXRlbV9pZF9oZXgYASABKAkSEQoJdG9waWNfaGV4GAIgASgJEhAKCGhlYWRsaW5lGAMgASgJEgsKA3VybBgEIAEoCRIMCgRib2R5GAUgASgJEiUKB3N1YnR5cGUYBiABKA4yFC5jb2lubmV3cy52MS5TdWJ0eXBlEgwKBGxhbmcYByABKAkSDAoEbnNmdxgIIAEoCBIWCg5hdXRob3JfeHBrX2hleBgJIAEoCRIUCgxibG9ja19oZWlnaHQYCiABKA0SLgoKYmxvY2tfdGltZRgLIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASFQoNY29tbWVudF9jb3VudBgNIAEoBRIMCgR0eGlkGA8gASgJEgwKBHZvdXQYECABKA0SEAoIZmVlX3NhdHMYEyABKANKBAgMEA1KBAgOEA9KBAgREBJKBAgSEBNSBnBvaW50c1IFc2NvcmVSB3Vwdm90ZXNSCWRvd252b3RlcyKaAgoHQ29tbWVudBITCgtpdGVtX2lkX2hleBgBIAEoCRIVCg1wYXJlbnRfaWRfaGV4GAIgASgJEhYKDmF1dGhvcl94cGtfaGV4GAMgASgJEgwKBGJvZHkYBCABKAkSCwoDdXJsGAUgASgJEgwKBGxhbmcYBiABKAkSEwoLcmVwbHlfcXVvdGUYByABKAkSFAoMYmxvY2tfaGVpZ2h0GAggASgNEi4KCmJsb2NrX3RpbWUYCSABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEgwKBHR4aWQYDCABKAkSDAoEdm91dBgNIAEoDRIQCghmZWVfc2F0cxgOIAEoA0oECAoQC0oECAsQDFIGcG9pbnRzUgVzY29yZSJmCgVUb3BpYxIRCgl0b3BpY19oZXgYASABKAkSDAoEbmFtZRgCIAEoCRIWCg5yZXRlbnRpb25fZGF5cxgDIAEoDRIWCg5jcmVhdGVkX2hlaWdodBgEIAEoDRIMCgR0eGlkGAUgASgJIpMBChRMaXN0RnJvbnRQYWdlUmVxdWVzdBINCgVsaW1pdBgBIAEoDRIOCgZvZmZzZXQYAiABKA0SKgoHc3VidHlwZRgDIAEoDjIULmNvaW5uZXdzLnYxLlN1YnR5cGVIAIgBARIWCgl0b3BpY19oZXgYBCABKAlIAYgBAUIKCghfc3VidHlwZUIMCgpfdG9waWNfaGV4IjkKFUxpc3RGcm9udFBhZ2VSZXNwb25zZRIgCgVpdGVtcxgBIAMoCzIRLmNvaW5uZXdzLnYxLkl0ZW0ikQEKEkxpc3ROZXdGZWVkUmVxdWVzdBINCgVsaW1pdBgBIAEoDRIOCgZvZmZzZXQYAiABKA0SKgoHc3VidHlwZRgDIAEoDjIULmNvaW5uZXdzLnYxLlN1YnR5cGVIAIgBARIWCgl0b3BpY19oZXgYBCABKAlIAYgBAUIKCghfc3VidHlwZUIMCgpfdG9waWNfaGV4IjcKE0xpc3ROZXdGZWVkUmVzcG9uc2USIAoFaXRlbXMYASADKAsyES5jb2lubmV3cy52MS5JdGVtIiUKDkdldEl0ZW1SZXF1ZXN0EhMKC2l0ZW1faWRfaGV4GAEgASgJIjIKD0dldEl0ZW1SZXNwb25zZRIfCgRpdGVtGAEgASgLMhEuY29pbm5ld3MudjEuSXRlbSIoChFMaXN0VGhyZWFkUmVxdWVzdBITCgtyb290X2lkX2hleBgBIAEoCSI8ChJMaXN0VGhyZWFkUmVzcG9uc2USJgoIY29tbWVudHMYASADKAsyFC5jb2lubmV3cy52MS5Db21tZW50IkwKE0xpc3RCeUF1dGhvclJlcXVlc3QSFgoOYXV0aG9yX3hwa19oZXgYASABKAkSDQoFbGltaXQYAiABKA0SDgoGb2Zmc2V0GAMgASgNIjgKFExpc3RCeUF1dGhvclJlc3BvbnNlEiAKBWl0ZW1zGAEgAygLMhEuY29pbm5ld3MudjEuSXRlbSJGChJMaXN0QnlUb3BpY1JlcXVlc3QSEQoJdG9waWNfaGV4GAEgASgJEg0KBWxpbWl0GAIgASgNEg4KBm9mZnNldBgDIAEoDSI3ChNMaXN0QnlUb3BpY1Jlc3BvbnNlEiAKBWl0ZW1zGAEgAygLMhEuY29pbm5ld3MudjEuSXRlbSI4ChJMaXN0VG9waWNzUmVzcG9uc2USIgoGdG9waWNzGAEgAygLMhIuY29pbm5ld3MudjEuVG9waWMqcwoHU3VidHlwZRIQCgxTVUJUWVBFX0xJTksQABIQCgxTVUJUWVBFX1RFWFQQARIPCgtTVUJUWVBFX0FTSxACEhAKDFNVQlRZUEVfU0hPVxADEhAKDFNVQlRZUEVfUE9MTBAEEg8KC1NVQlRZUEVfSk9CEAUyvgQKD0NvaW5OZXdzU2VydmljZRJWCg1MaXN0RnJvbnRQYWdlEiEuY29pbm5ld3MudjEuTGlzdEZyb250UGFnZVJlcXVlc3QaIi5jb2lubmV3cy52MS5MaXN0RnJvbnRQYWdlUmVzcG9uc2USUAoLTGlzdE5ld0ZlZWQSHy5jb2lubmV3cy52MS5MaXN0TmV3RmVlZFJlcXVlc3QaIC5jb2lubmV3cy52MS5MaXN0TmV3RmVlZFJlc3BvbnNlEkQKB0dldEl0ZW0SGy5jb2lubmV3cy52MS5HZXRJdGVtUmVxdWVzdBocLmNvaW5uZXdzLnYxLkdldEl0ZW1SZXNwb25zZRJNCgpMaXN0VGhyZWFkEh4uY29pbm5ld3MudjEuTGlzdFRocmVhZFJlcXVlc3QaHy5jb2lubmV3cy52MS5MaXN0VGhyZWFkUmVzcG9uc2USUwoMTGlzdEJ5QXV0aG9yEiAuY29pbm5ld3MudjEuTGlzdEJ5QXV0aG9yUmVxdWVzdBohLmNvaW5uZXdzLnYxLkxpc3RCeUF1dGhvclJlc3BvbnNlElAKC0xpc3RCeVRvcGljEh8uY29pbm5ld3MudjEuTGlzdEJ5VG9waWNSZXF1ZXN0GiAuY29pbm5ld3MudjEuTGlzdEJ5VG9waWNSZXNwb25zZRJFCgpMaXN0VG9waWNzEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5Gh8uY29pbm5ld3MudjEuTGlzdFRvcGljc1Jlc3BvbnNlYgZwcm90bzM", [file_google_protobuf_empty, file_google_protobuf_timestamp]); + fileDesc("Chpjb2lubmV3cy92MS9jb2lubmV3cy5wcm90bxILY29pbm5ld3MudjEipgMKBEl0ZW0SEwoLaXRlbV9pZF9oZXgYASABKAkSEQoJdG9waWNfaGV4GAIgASgJEhAKCGhlYWRsaW5lGAMgASgJEgsKA3VybBgEIAEoCRIMCgRib2R5GAUgASgJEiUKB3N1YnR5cGUYBiABKA4yFC5jb2lubmV3cy52MS5TdWJ0eXBlEgwKBGxhbmcYByABKAkSDAoEbnNmdxgIIAEoCBIWCg5hdXRob3JfeHBrX2hleBgJIAEoCRIUCgxibG9ja19oZWlnaHQYCiABKA0SLgoKYmxvY2tfdGltZRgLIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASFQoNY29tbWVudF9jb3VudBgNIAEoBRIMCgR0eGlkGA8gASgJEgwKBHZvdXQYECABKA0SEAoIZmVlX3NhdHMYEyABKAMSKAoJcmVhY3Rpb25zGBQgAygLMhUuY29pbm5ld3MudjEuUmVhY3Rpb25KBAgMEA1KBAgOEA9KBAgREBJKBAgSEBNSBnBvaW50c1IFc2NvcmVSB3Vwdm90ZXNSCWRvd252b3RlcyLEAgoHQ29tbWVudBITCgtpdGVtX2lkX2hleBgBIAEoCRIVCg1wYXJlbnRfaWRfaGV4GAIgASgJEhYKDmF1dGhvcl94cGtfaGV4GAMgASgJEgwKBGJvZHkYBCABKAkSCwoDdXJsGAUgASgJEgwKBGxhbmcYBiABKAkSEwoLcmVwbHlfcXVvdGUYByABKAkSFAoMYmxvY2tfaGVpZ2h0GAggASgNEi4KCmJsb2NrX3RpbWUYCSABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEgwKBHR4aWQYDCABKAkSDAoEdm91dBgNIAEoDRIQCghmZWVfc2F0cxgOIAEoAxIoCglyZWFjdGlvbnMYDyADKAsyFS5jb2lubmV3cy52MS5SZWFjdGlvbkoECAoQC0oECAsQDFIGcG9pbnRzUgVzY29yZSIrCghSZWFjdGlvbhINCgVlbW9qaRgBIAEoCRIQCghmZWVfc2F0cxgCIAEoAyJmCgVUb3BpYxIRCgl0b3BpY19oZXgYASABKAkSDAoEbmFtZRgCIAEoCRIWCg5yZXRlbnRpb25fZGF5cxgDIAEoDRIWCg5jcmVhdGVkX2hlaWdodBgEIAEoDRIMCgR0eGlkGAUgASgJIpMBChRMaXN0RnJvbnRQYWdlUmVxdWVzdBINCgVsaW1pdBgBIAEoDRIOCgZvZmZzZXQYAiABKA0SKgoHc3VidHlwZRgDIAEoDjIULmNvaW5uZXdzLnYxLlN1YnR5cGVIAIgBARIWCgl0b3BpY19oZXgYBCABKAlIAYgBAUIKCghfc3VidHlwZUIMCgpfdG9waWNfaGV4IjkKFUxpc3RGcm9udFBhZ2VSZXNwb25zZRIgCgVpdGVtcxgBIAMoCzIRLmNvaW5uZXdzLnYxLkl0ZW0ikQEKEkxpc3ROZXdGZWVkUmVxdWVzdBINCgVsaW1pdBgBIAEoDRIOCgZvZmZzZXQYAiABKA0SKgoHc3VidHlwZRgDIAEoDjIULmNvaW5uZXdzLnYxLlN1YnR5cGVIAIgBARIWCgl0b3BpY19oZXgYBCABKAlIAYgBAUIKCghfc3VidHlwZUIMCgpfdG9waWNfaGV4IjcKE0xpc3ROZXdGZWVkUmVzcG9uc2USIAoFaXRlbXMYASADKAsyES5jb2lubmV3cy52MS5JdGVtIiUKDkdldEl0ZW1SZXF1ZXN0EhMKC2l0ZW1faWRfaGV4GAEgASgJIjIKD0dldEl0ZW1SZXNwb25zZRIfCgRpdGVtGAEgASgLMhEuY29pbm5ld3MudjEuSXRlbSIoChFMaXN0VGhyZWFkUmVxdWVzdBITCgtyb290X2lkX2hleBgBIAEoCSI8ChJMaXN0VGhyZWFkUmVzcG9uc2USJgoIY29tbWVudHMYASADKAsyFC5jb2lubmV3cy52MS5Db21tZW50IkwKE0xpc3RCeUF1dGhvclJlcXVlc3QSFgoOYXV0aG9yX3hwa19oZXgYASABKAkSDQoFbGltaXQYAiABKA0SDgoGb2Zmc2V0GAMgASgNIjgKFExpc3RCeUF1dGhvclJlc3BvbnNlEiAKBWl0ZW1zGAEgAygLMhEuY29pbm5ld3MudjEuSXRlbSJGChJMaXN0QnlUb3BpY1JlcXVlc3QSEQoJdG9waWNfaGV4GAEgASgJEg0KBWxpbWl0GAIgASgNEg4KBm9mZnNldBgDIAEoDSI3ChNMaXN0QnlUb3BpY1Jlc3BvbnNlEiAKBWl0ZW1zGAEgAygLMhEuY29pbm5ld3MudjEuSXRlbSI4ChJMaXN0VG9waWNzUmVzcG9uc2USIgoGdG9waWNzGAEgAygLMhIuY29pbm5ld3MudjEuVG9waWMqcwoHU3VidHlwZRIQCgxTVUJUWVBFX0xJTksQABIQCgxTVUJUWVBFX1RFWFQQARIPCgtTVUJUWVBFX0FTSxACEhAKDFNVQlRZUEVfU0hPVxADEhAKDFNVQlRZUEVfUE9MTBAEEg8KC1NVQlRZUEVfSk9CEAUyvgQKD0NvaW5OZXdzU2VydmljZRJWCg1MaXN0RnJvbnRQYWdlEiEuY29pbm5ld3MudjEuTGlzdEZyb250UGFnZVJlcXVlc3QaIi5jb2lubmV3cy52MS5MaXN0RnJvbnRQYWdlUmVzcG9uc2USUAoLTGlzdE5ld0ZlZWQSHy5jb2lubmV3cy52MS5MaXN0TmV3RmVlZFJlcXVlc3QaIC5jb2lubmV3cy52MS5MaXN0TmV3RmVlZFJlc3BvbnNlEkQKB0dldEl0ZW0SGy5jb2lubmV3cy52MS5HZXRJdGVtUmVxdWVzdBocLmNvaW5uZXdzLnYxLkdldEl0ZW1SZXNwb25zZRJNCgpMaXN0VGhyZWFkEh4uY29pbm5ld3MudjEuTGlzdFRocmVhZFJlcXVlc3QaHy5jb2lubmV3cy52MS5MaXN0VGhyZWFkUmVzcG9uc2USUwoMTGlzdEJ5QXV0aG9yEiAuY29pbm5ld3MudjEuTGlzdEJ5QXV0aG9yUmVxdWVzdBohLmNvaW5uZXdzLnYxLkxpc3RCeUF1dGhvclJlc3BvbnNlElAKC0xpc3RCeVRvcGljEh8uY29pbm5ld3MudjEuTGlzdEJ5VG9waWNSZXF1ZXN0GiAuY29pbm5ld3MudjEuTGlzdEJ5VG9waWNSZXNwb25zZRJFCgpMaXN0VG9waWNzEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5Gh8uY29pbm5ld3MudjEuTGlzdFRvcGljc1Jlc3BvbnNlYgZwcm90bzM", [file_google_protobuf_empty, file_google_protobuf_timestamp]); /** * Describes the message coinnews.v1.Item. @@ -25,103 +25,110 @@ export const ItemSchema = /*@__PURE__*/ export const CommentSchema = /*@__PURE__*/ messageDesc(file_coinnews_v1_coinnews, 1); +/** + * Describes the message coinnews.v1.Reaction. + * Use `create(ReactionSchema)` to create a new message. + */ +export const ReactionSchema = /*@__PURE__*/ + messageDesc(file_coinnews_v1_coinnews, 2); + /** * Describes the message coinnews.v1.Topic. * Use `create(TopicSchema)` to create a new message. */ export const TopicSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 2); + messageDesc(file_coinnews_v1_coinnews, 3); /** * Describes the message coinnews.v1.ListFrontPageRequest. * Use `create(ListFrontPageRequestSchema)` to create a new message. */ export const ListFrontPageRequestSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 3); + messageDesc(file_coinnews_v1_coinnews, 4); /** * Describes the message coinnews.v1.ListFrontPageResponse. * Use `create(ListFrontPageResponseSchema)` to create a new message. */ export const ListFrontPageResponseSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 4); + messageDesc(file_coinnews_v1_coinnews, 5); /** * Describes the message coinnews.v1.ListNewFeedRequest. * Use `create(ListNewFeedRequestSchema)` to create a new message. */ export const ListNewFeedRequestSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 5); + messageDesc(file_coinnews_v1_coinnews, 6); /** * Describes the message coinnews.v1.ListNewFeedResponse. * Use `create(ListNewFeedResponseSchema)` to create a new message. */ export const ListNewFeedResponseSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 6); + messageDesc(file_coinnews_v1_coinnews, 7); /** * Describes the message coinnews.v1.GetItemRequest. * Use `create(GetItemRequestSchema)` to create a new message. */ export const GetItemRequestSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 7); + messageDesc(file_coinnews_v1_coinnews, 8); /** * Describes the message coinnews.v1.GetItemResponse. * Use `create(GetItemResponseSchema)` to create a new message. */ export const GetItemResponseSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 8); + messageDesc(file_coinnews_v1_coinnews, 9); /** * Describes the message coinnews.v1.ListThreadRequest. * Use `create(ListThreadRequestSchema)` to create a new message. */ export const ListThreadRequestSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 9); + messageDesc(file_coinnews_v1_coinnews, 10); /** * Describes the message coinnews.v1.ListThreadResponse. * Use `create(ListThreadResponseSchema)` to create a new message. */ export const ListThreadResponseSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 10); + messageDesc(file_coinnews_v1_coinnews, 11); /** * Describes the message coinnews.v1.ListByAuthorRequest. * Use `create(ListByAuthorRequestSchema)` to create a new message. */ export const ListByAuthorRequestSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 11); + messageDesc(file_coinnews_v1_coinnews, 12); /** * Describes the message coinnews.v1.ListByAuthorResponse. * Use `create(ListByAuthorResponseSchema)` to create a new message. */ export const ListByAuthorResponseSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 12); + messageDesc(file_coinnews_v1_coinnews, 13); /** * Describes the message coinnews.v1.ListByTopicRequest. * Use `create(ListByTopicRequestSchema)` to create a new message. */ export const ListByTopicRequestSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 13); + messageDesc(file_coinnews_v1_coinnews, 14); /** * Describes the message coinnews.v1.ListByTopicResponse. * Use `create(ListByTopicResponseSchema)` to create a new message. */ export const ListByTopicResponseSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 14); + messageDesc(file_coinnews_v1_coinnews, 15); /** * Describes the message coinnews.v1.ListTopicsResponse. * Use `create(ListTopicsResponseSchema)` to create a new message. */ export const ListTopicsResponseSchema = /*@__PURE__*/ - messageDesc(file_coinnews_v1_coinnews, 15); + messageDesc(file_coinnews_v1_coinnews, 16); /** * Describes the enum coinnews.v1.Subtype. diff --git a/coinnews/server/api/api.go b/coinnews/server/api/api.go index aeadf068b8..6638e3b804 100644 --- a/coinnews/server/api/api.go +++ b/coinnews/server/api/api.go @@ -36,7 +36,11 @@ func (h *Handler) ListFrontPage(ctx context.Context, req *pb.ListFrontPageReques if err != nil { return nil, h.errInternal(err) } - return &pb.ListFrontPageResponse{Items: marshalItems(items)}, nil + out, err := h.marshalItems(ctx, items) + if err != nil { + return nil, err + } + return &pb.ListFrontPageResponse{Items: out}, nil } func (h *Handler) ListNewFeed(ctx context.Context, req *pb.ListNewFeedRequest) (*pb.ListNewFeedResponse, error) { @@ -48,7 +52,11 @@ func (h *Handler) ListNewFeed(ctx context.Context, req *pb.ListNewFeedRequest) ( if err != nil { return nil, h.errInternal(err) } - return &pb.ListNewFeedResponse{Items: marshalItems(items)}, nil + out, err := h.marshalItems(ctx, items) + if err != nil { + return nil, err + } + return &pb.ListNewFeedResponse{Items: out}, nil } func (h *Handler) GetItem(ctx context.Context, req *pb.GetItemRequest) (*pb.GetItemResponse, error) { @@ -63,7 +71,11 @@ func (h *Handler) GetItem(ctx context.Context, req *pb.GetItemRequest) (*pb.GetI if err != nil { return nil, h.errInternal(err) } - return &pb.GetItemResponse{Item: marshalItem(fi)}, nil + out, err := h.marshalItems(ctx, []store.FeedItem{fi}) + if err != nil { + return nil, err + } + return &pb.GetItemResponse{Item: out[0]}, nil } func (h *Handler) ListThread(ctx context.Context, req *pb.ListThreadRequest) (*pb.ListThreadResponse, error) { @@ -75,9 +87,17 @@ func (h *Handler) ListThread(ctx context.Context, req *pb.ListThreadRequest) (*p if err != nil { return nil, h.errInternal(err) } + ids := make([]codec.ItemID, len(rows)) + for i, r := range rows { + ids[i] = r.ItemID + } + reactions, err := store.ListReactions(ctx, h.DB, ids) + if err != nil { + return nil, h.errInternal(err) + } out := make([]*pb.Comment, len(rows)) for i, r := range rows { - out[i] = marshalComment(r) + out[i] = marshalComment(r, reactions[r.ItemID]) } return &pb.ListThreadResponse{Comments: out}, nil } @@ -93,7 +113,11 @@ func (h *Handler) ListByAuthor(ctx context.Context, req *pb.ListByAuthorRequest) if err != nil { return nil, h.errInternal(err) } - return &pb.ListByAuthorResponse{Items: marshalItems(items)}, nil + out, err := h.marshalItems(ctx, items) + if err != nil { + return nil, err + } + return &pb.ListByAuthorResponse{Items: out}, nil } func (h *Handler) ListByTopic(ctx context.Context, req *pb.ListByTopicRequest) (*pb.ListByTopicResponse, error) { @@ -110,7 +134,11 @@ func (h *Handler) ListByTopic(ctx context.Context, req *pb.ListByTopicRequest) ( if err != nil { return nil, h.errInternal(err) } - return &pb.ListByTopicResponse{Items: marshalItems(items)}, nil + out, err := h.marshalItems(ctx, items) + if err != nil { + return nil, err + } + return &pb.ListByTopicResponse{Items: out}, nil } func (h *Handler) ListTopics(ctx context.Context, _ *emptypb.Empty) (*pb.ListTopicsResponse, error) { @@ -157,15 +185,31 @@ func parseTopic(s string) (codec.Topic, error) { return t, nil } -func marshalItems(in []store.FeedItem) []*pb.Item { +func (h *Handler) marshalItems(ctx context.Context, in []store.FeedItem) ([]*pb.Item, error) { + ids := make([]codec.ItemID, len(in)) + for i, fi := range in { + ids[i] = fi.ItemID + } + reactions, err := store.ListReactions(ctx, h.DB, ids) + if err != nil { + return nil, h.errInternal(err) + } out := make([]*pb.Item, len(in)) for i, fi := range in { - out[i] = marshalItem(fi) + out[i] = marshalItem(fi, reactions[fi.ItemID]) + } + return out, nil +} + +func marshalReactions(in []store.Reaction) []*pb.Reaction { + out := make([]*pb.Reaction, len(in)) + for i, r := range in { + out[i] = &pb.Reaction{Emoji: r.Emoji, FeeSats: r.FeeSats} } return out } -func marshalItem(fi store.FeedItem) *pb.Item { +func marshalItem(fi store.FeedItem, reactions []store.Reaction) *pb.Item { return &pb.Item{ ItemIdHex: hex.EncodeToString(fi.ItemID[:]), TopicHex: hex.EncodeToString(fi.Topic[:]), @@ -182,10 +226,11 @@ func marshalItem(fi store.FeedItem) *pb.Item { Txid: fi.TxID, Vout: fi.Vout, FeeSats: fi.FeeSats, + Reactions: marshalReactions(reactions), } } -func marshalComment(c store.CommentRow) *pb.Comment { +func marshalComment(c store.CommentRow, reactions []store.Reaction) *pb.Comment { return &pb.Comment{ ItemIdHex: hex.EncodeToString(c.ItemID[:]), ParentIdHex: hex.EncodeToString(c.Parent[:]), @@ -199,6 +244,7 @@ func marshalComment(c store.CommentRow) *pb.Comment { Txid: c.TxID, Vout: c.Vout, FeeSats: c.FeeSats, + Reactions: marshalReactions(reactions), } } diff --git a/coinnews/server/api/api_test.go b/coinnews/server/api/api_test.go index fec468fbdb..a4f2aed73b 100644 --- a/coinnews/server/api/api_test.go +++ b/coinnews/server/api/api_test.go @@ -295,7 +295,7 @@ func TestHandler_InvalidUTF8(t *testing.T) { assert.Equal(t, "a\ufffd", front.Items[0].Headline) assert.Equal(t, "a\ufffd", front.Items[0].Url) - comment := marshalComment(store.CommentRow{Body: string(bad), URL: string(bad), Lang: string(bad), ReplyQuote: string(bad)}) + comment := marshalComment(store.CommentRow{Body: string(bad), URL: string(bad), Lang: string(bad), ReplyQuote: string(bad)}, nil) _, err = proto.Marshal(comment) require.NoError(t, err) } diff --git a/coinnews/server/gen/coinnews/v1/coinnews.pb.go b/coinnews/server/gen/coinnews/v1/coinnews.pb.go index 35ecf0346c..564e1e7b00 100644 --- a/coinnews/server/gen/coinnews/v1/coinnews.pb.go +++ b/coinnews/server/gen/coinnews/v1/coinnews.pb.go @@ -101,7 +101,9 @@ type Item struct { Txid string `protobuf:"bytes,15,opt,name=txid,proto3" json:"txid,omitempty"` Vout uint32 `protobuf:"varint,16,opt,name=vout,proto3" json:"vout,omitempty"` // Fee of the transaction that carries the item, in sats. - FeeSats int64 `protobuf:"varint,19,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + FeeSats int64 `protobuf:"varint,19,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + // Reactions to the item, highest total first. + Reactions []*Reaction `protobuf:"bytes,20,rep,name=reactions,proto3" json:"reactions,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -241,6 +243,13 @@ func (x *Item) GetFeeSats() int64 { return 0 } +func (x *Item) GetReactions() []*Reaction { + if x != nil { + return x.Reactions + } + return nil +} + type Comment struct { state protoimpl.MessageState `protogen:"open.v1"` ItemIdHex string `protobuf:"bytes,1,opt,name=item_id_hex,json=itemIdHex,proto3" json:"item_id_hex,omitempty"` @@ -256,7 +265,9 @@ type Comment struct { Txid string `protobuf:"bytes,12,opt,name=txid,proto3" json:"txid,omitempty"` Vout uint32 `protobuf:"varint,13,opt,name=vout,proto3" json:"vout,omitempty"` // Fee of the transaction that carries the comment, in sats. - FeeSats int64 `protobuf:"varint,14,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + FeeSats int64 `protobuf:"varint,14,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + // Reactions to the comment, highest total first. + Reactions []*Reaction `protobuf:"bytes,15,rep,name=reactions,proto3" json:"reactions,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -375,6 +386,67 @@ func (x *Comment) GetFeeSats() int64 { return 0 } +func (x *Comment) GetReactions() []*Reaction { + if x != nil { + return x.Reactions + } + return nil +} + +// The fee total of one emoji on an item. +type Reaction struct { + state protoimpl.MessageState `protogen:"open.v1"` + Emoji string `protobuf:"bytes,1,opt,name=emoji,proto3" json:"emoji,omitempty"` + // Sum of the fees of every reaction with this emoji, in sats. + FeeSats int64 `protobuf:"varint,2,opt,name=fee_sats,json=feeSats,proto3" json:"fee_sats,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Reaction) Reset() { + *x = Reaction{} + mi := &file_coinnews_v1_coinnews_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Reaction) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Reaction) ProtoMessage() {} + +func (x *Reaction) ProtoReflect() protoreflect.Message { + mi := &file_coinnews_v1_coinnews_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Reaction.ProtoReflect.Descriptor instead. +func (*Reaction) Descriptor() ([]byte, []int) { + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{2} +} + +func (x *Reaction) GetEmoji() string { + if x != nil { + return x.Emoji + } + return "" +} + +func (x *Reaction) GetFeeSats() int64 { + if x != nil { + return x.FeeSats + } + return 0 +} + type Topic struct { state protoimpl.MessageState `protogen:"open.v1"` TopicHex string `protobuf:"bytes,1,opt,name=topic_hex,json=topicHex,proto3" json:"topic_hex,omitempty"` @@ -388,7 +460,7 @@ type Topic struct { func (x *Topic) Reset() { *x = Topic{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[2] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -400,7 +472,7 @@ func (x *Topic) String() string { func (*Topic) ProtoMessage() {} func (x *Topic) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[2] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -413,7 +485,7 @@ func (x *Topic) ProtoReflect() protoreflect.Message { // Deprecated: Use Topic.ProtoReflect.Descriptor instead. func (*Topic) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{2} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{3} } func (x *Topic) GetTopicHex() string { @@ -463,7 +535,7 @@ type ListFrontPageRequest struct { func (x *ListFrontPageRequest) Reset() { *x = ListFrontPageRequest{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[3] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -475,7 +547,7 @@ func (x *ListFrontPageRequest) String() string { func (*ListFrontPageRequest) ProtoMessage() {} func (x *ListFrontPageRequest) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[3] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -488,7 +560,7 @@ func (x *ListFrontPageRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListFrontPageRequest.ProtoReflect.Descriptor instead. func (*ListFrontPageRequest) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{3} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{4} } func (x *ListFrontPageRequest) GetLimit() uint32 { @@ -528,7 +600,7 @@ type ListFrontPageResponse struct { func (x *ListFrontPageResponse) Reset() { *x = ListFrontPageResponse{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[4] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -540,7 +612,7 @@ func (x *ListFrontPageResponse) String() string { func (*ListFrontPageResponse) ProtoMessage() {} func (x *ListFrontPageResponse) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[4] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -553,7 +625,7 @@ func (x *ListFrontPageResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListFrontPageResponse.ProtoReflect.Descriptor instead. func (*ListFrontPageResponse) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{4} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{5} } func (x *ListFrontPageResponse) GetItems() []*Item { @@ -575,7 +647,7 @@ type ListNewFeedRequest struct { func (x *ListNewFeedRequest) Reset() { *x = ListNewFeedRequest{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[5] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -587,7 +659,7 @@ func (x *ListNewFeedRequest) String() string { func (*ListNewFeedRequest) ProtoMessage() {} func (x *ListNewFeedRequest) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[5] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -600,7 +672,7 @@ func (x *ListNewFeedRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListNewFeedRequest.ProtoReflect.Descriptor instead. func (*ListNewFeedRequest) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{5} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{6} } func (x *ListNewFeedRequest) GetLimit() uint32 { @@ -640,7 +712,7 @@ type ListNewFeedResponse struct { func (x *ListNewFeedResponse) Reset() { *x = ListNewFeedResponse{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[6] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -652,7 +724,7 @@ func (x *ListNewFeedResponse) String() string { func (*ListNewFeedResponse) ProtoMessage() {} func (x *ListNewFeedResponse) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[6] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -665,7 +737,7 @@ func (x *ListNewFeedResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListNewFeedResponse.ProtoReflect.Descriptor instead. func (*ListNewFeedResponse) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{6} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{7} } func (x *ListNewFeedResponse) GetItems() []*Item { @@ -684,7 +756,7 @@ type GetItemRequest struct { func (x *GetItemRequest) Reset() { *x = GetItemRequest{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[7] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -696,7 +768,7 @@ func (x *GetItemRequest) String() string { func (*GetItemRequest) ProtoMessage() {} func (x *GetItemRequest) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[7] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -709,7 +781,7 @@ func (x *GetItemRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetItemRequest.ProtoReflect.Descriptor instead. func (*GetItemRequest) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{7} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{8} } func (x *GetItemRequest) GetItemIdHex() string { @@ -728,7 +800,7 @@ type GetItemResponse struct { func (x *GetItemResponse) Reset() { *x = GetItemResponse{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[8] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -740,7 +812,7 @@ func (x *GetItemResponse) String() string { func (*GetItemResponse) ProtoMessage() {} func (x *GetItemResponse) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[8] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -753,7 +825,7 @@ func (x *GetItemResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetItemResponse.ProtoReflect.Descriptor instead. func (*GetItemResponse) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{8} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{9} } func (x *GetItemResponse) GetItem() *Item { @@ -772,7 +844,7 @@ type ListThreadRequest struct { func (x *ListThreadRequest) Reset() { *x = ListThreadRequest{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[9] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -784,7 +856,7 @@ func (x *ListThreadRequest) String() string { func (*ListThreadRequest) ProtoMessage() {} func (x *ListThreadRequest) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[9] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -797,7 +869,7 @@ func (x *ListThreadRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListThreadRequest.ProtoReflect.Descriptor instead. func (*ListThreadRequest) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{9} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{10} } func (x *ListThreadRequest) GetRootIdHex() string { @@ -816,7 +888,7 @@ type ListThreadResponse struct { func (x *ListThreadResponse) Reset() { *x = ListThreadResponse{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[10] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -828,7 +900,7 @@ func (x *ListThreadResponse) String() string { func (*ListThreadResponse) ProtoMessage() {} func (x *ListThreadResponse) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[10] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -841,7 +913,7 @@ func (x *ListThreadResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListThreadResponse.ProtoReflect.Descriptor instead. func (*ListThreadResponse) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{10} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{11} } func (x *ListThreadResponse) GetComments() []*Comment { @@ -862,7 +934,7 @@ type ListByAuthorRequest struct { func (x *ListByAuthorRequest) Reset() { *x = ListByAuthorRequest{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[11] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -874,7 +946,7 @@ func (x *ListByAuthorRequest) String() string { func (*ListByAuthorRequest) ProtoMessage() {} func (x *ListByAuthorRequest) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[11] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -887,7 +959,7 @@ func (x *ListByAuthorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListByAuthorRequest.ProtoReflect.Descriptor instead. func (*ListByAuthorRequest) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{11} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{12} } func (x *ListByAuthorRequest) GetAuthorXpkHex() string { @@ -920,7 +992,7 @@ type ListByAuthorResponse struct { func (x *ListByAuthorResponse) Reset() { *x = ListByAuthorResponse{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[12] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -932,7 +1004,7 @@ func (x *ListByAuthorResponse) String() string { func (*ListByAuthorResponse) ProtoMessage() {} func (x *ListByAuthorResponse) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[12] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -945,7 +1017,7 @@ func (x *ListByAuthorResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListByAuthorResponse.ProtoReflect.Descriptor instead. func (*ListByAuthorResponse) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{12} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{13} } func (x *ListByAuthorResponse) GetItems() []*Item { @@ -966,7 +1038,7 @@ type ListByTopicRequest struct { func (x *ListByTopicRequest) Reset() { *x = ListByTopicRequest{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[13] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -978,7 +1050,7 @@ func (x *ListByTopicRequest) String() string { func (*ListByTopicRequest) ProtoMessage() {} func (x *ListByTopicRequest) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[13] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -991,7 +1063,7 @@ func (x *ListByTopicRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListByTopicRequest.ProtoReflect.Descriptor instead. func (*ListByTopicRequest) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{13} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{14} } func (x *ListByTopicRequest) GetTopicHex() string { @@ -1024,7 +1096,7 @@ type ListByTopicResponse struct { func (x *ListByTopicResponse) Reset() { *x = ListByTopicResponse{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[14] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1036,7 +1108,7 @@ func (x *ListByTopicResponse) String() string { func (*ListByTopicResponse) ProtoMessage() {} func (x *ListByTopicResponse) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[14] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1049,7 +1121,7 @@ func (x *ListByTopicResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListByTopicResponse.ProtoReflect.Descriptor instead. func (*ListByTopicResponse) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{14} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{15} } func (x *ListByTopicResponse) GetItems() []*Item { @@ -1068,7 +1140,7 @@ type ListTopicsResponse struct { func (x *ListTopicsResponse) Reset() { *x = ListTopicsResponse{} - mi := &file_coinnews_v1_coinnews_proto_msgTypes[15] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1080,7 +1152,7 @@ func (x *ListTopicsResponse) String() string { func (*ListTopicsResponse) ProtoMessage() {} func (x *ListTopicsResponse) ProtoReflect() protoreflect.Message { - mi := &file_coinnews_v1_coinnews_proto_msgTypes[15] + mi := &file_coinnews_v1_coinnews_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1093,7 +1165,7 @@ func (x *ListTopicsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTopicsResponse.ProtoReflect.Descriptor instead. func (*ListTopicsResponse) Descriptor() ([]byte, []int) { - return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{15} + return file_coinnews_v1_coinnews_proto_rawDescGZIP(), []int{16} } func (x *ListTopicsResponse) GetTopics() []*Topic { @@ -1107,7 +1179,7 @@ var File_coinnews_v1_coinnews_proto protoreflect.FileDescriptor const file_coinnews_v1_coinnews_proto_rawDesc = "" + "\n" + - "\x1acoinnews/v1/coinnews.proto\x12\vcoinnews.v1\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x84\x04\n" + + "\x1acoinnews/v1/coinnews.proto\x12\vcoinnews.v1\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\xb9\x04\n" + "\x04Item\x12\x1e\n" + "\vitem_id_hex\x18\x01 \x01(\tR\titemIdHex\x12\x1b\n" + "\ttopic_hex\x18\x02 \x01(\tR\btopicHex\x12\x1a\n" + @@ -1125,7 +1197,8 @@ const file_coinnews_v1_coinnews_proto_rawDesc = "" + "\rcomment_count\x18\r \x01(\x05R\fcommentCount\x12\x12\n" + "\x04txid\x18\x0f \x01(\tR\x04txid\x12\x12\n" + "\x04vout\x18\x10 \x01(\rR\x04vout\x12\x19\n" + - "\bfee_sats\x18\x13 \x01(\x03R\afeeSatsJ\x04\b\f\x10\rJ\x04\b\x0e\x10\x0fJ\x04\b\x11\x10\x12J\x04\b\x12\x10\x13R\x06pointsR\x05scoreR\aupvotesR\tdownvotes\"\x8a\x03\n" + + "\bfee_sats\x18\x13 \x01(\x03R\afeeSats\x123\n" + + "\treactions\x18\x14 \x03(\v2\x15.coinnews.v1.ReactionR\treactionsJ\x04\b\f\x10\rJ\x04\b\x0e\x10\x0fJ\x04\b\x11\x10\x12J\x04\b\x12\x10\x13R\x06pointsR\x05scoreR\aupvotesR\tdownvotes\"\xbf\x03\n" + "\aComment\x12\x1e\n" + "\vitem_id_hex\x18\x01 \x01(\tR\titemIdHex\x12\"\n" + "\rparent_id_hex\x18\x02 \x01(\tR\vparentIdHex\x12$\n" + @@ -1140,8 +1213,12 @@ const file_coinnews_v1_coinnews_proto_rawDesc = "" + "block_time\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\tblockTime\x12\x12\n" + "\x04txid\x18\f \x01(\tR\x04txid\x12\x12\n" + "\x04vout\x18\r \x01(\rR\x04vout\x12\x19\n" + - "\bfee_sats\x18\x0e \x01(\x03R\afeeSatsJ\x04\b\n" + - "\x10\vJ\x04\b\v\x10\fR\x06pointsR\x05score\"\x9a\x01\n" + + "\bfee_sats\x18\x0e \x01(\x03R\afeeSats\x123\n" + + "\treactions\x18\x0f \x03(\v2\x15.coinnews.v1.ReactionR\treactionsJ\x04\b\n" + + "\x10\vJ\x04\b\v\x10\fR\x06pointsR\x05score\";\n" + + "\bReaction\x12\x14\n" + + "\x05emoji\x18\x01 \x01(\tR\x05emoji\x12\x19\n" + + "\bfee_sats\x18\x02 \x01(\x03R\afeeSats\"\x9a\x01\n" + "\x05Topic\x12\x1b\n" + "\ttopic_hex\x18\x01 \x01(\tR\btopicHex\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12%\n" + @@ -1224,60 +1301,63 @@ func file_coinnews_v1_coinnews_proto_rawDescGZIP() []byte { } var file_coinnews_v1_coinnews_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_coinnews_v1_coinnews_proto_msgTypes = make([]protoimpl.MessageInfo, 16) +var file_coinnews_v1_coinnews_proto_msgTypes = make([]protoimpl.MessageInfo, 17) var file_coinnews_v1_coinnews_proto_goTypes = []any{ (Subtype)(0), // 0: coinnews.v1.Subtype (*Item)(nil), // 1: coinnews.v1.Item (*Comment)(nil), // 2: coinnews.v1.Comment - (*Topic)(nil), // 3: coinnews.v1.Topic - (*ListFrontPageRequest)(nil), // 4: coinnews.v1.ListFrontPageRequest - (*ListFrontPageResponse)(nil), // 5: coinnews.v1.ListFrontPageResponse - (*ListNewFeedRequest)(nil), // 6: coinnews.v1.ListNewFeedRequest - (*ListNewFeedResponse)(nil), // 7: coinnews.v1.ListNewFeedResponse - (*GetItemRequest)(nil), // 8: coinnews.v1.GetItemRequest - (*GetItemResponse)(nil), // 9: coinnews.v1.GetItemResponse - (*ListThreadRequest)(nil), // 10: coinnews.v1.ListThreadRequest - (*ListThreadResponse)(nil), // 11: coinnews.v1.ListThreadResponse - (*ListByAuthorRequest)(nil), // 12: coinnews.v1.ListByAuthorRequest - (*ListByAuthorResponse)(nil), // 13: coinnews.v1.ListByAuthorResponse - (*ListByTopicRequest)(nil), // 14: coinnews.v1.ListByTopicRequest - (*ListByTopicResponse)(nil), // 15: coinnews.v1.ListByTopicResponse - (*ListTopicsResponse)(nil), // 16: coinnews.v1.ListTopicsResponse - (*timestamppb.Timestamp)(nil), // 17: google.protobuf.Timestamp - (*emptypb.Empty)(nil), // 18: google.protobuf.Empty + (*Reaction)(nil), // 3: coinnews.v1.Reaction + (*Topic)(nil), // 4: coinnews.v1.Topic + (*ListFrontPageRequest)(nil), // 5: coinnews.v1.ListFrontPageRequest + (*ListFrontPageResponse)(nil), // 6: coinnews.v1.ListFrontPageResponse + (*ListNewFeedRequest)(nil), // 7: coinnews.v1.ListNewFeedRequest + (*ListNewFeedResponse)(nil), // 8: coinnews.v1.ListNewFeedResponse + (*GetItemRequest)(nil), // 9: coinnews.v1.GetItemRequest + (*GetItemResponse)(nil), // 10: coinnews.v1.GetItemResponse + (*ListThreadRequest)(nil), // 11: coinnews.v1.ListThreadRequest + (*ListThreadResponse)(nil), // 12: coinnews.v1.ListThreadResponse + (*ListByAuthorRequest)(nil), // 13: coinnews.v1.ListByAuthorRequest + (*ListByAuthorResponse)(nil), // 14: coinnews.v1.ListByAuthorResponse + (*ListByTopicRequest)(nil), // 15: coinnews.v1.ListByTopicRequest + (*ListByTopicResponse)(nil), // 16: coinnews.v1.ListByTopicResponse + (*ListTopicsResponse)(nil), // 17: coinnews.v1.ListTopicsResponse + (*timestamppb.Timestamp)(nil), // 18: google.protobuf.Timestamp + (*emptypb.Empty)(nil), // 19: google.protobuf.Empty } var file_coinnews_v1_coinnews_proto_depIdxs = []int32{ 0, // 0: coinnews.v1.Item.subtype:type_name -> coinnews.v1.Subtype - 17, // 1: coinnews.v1.Item.block_time:type_name -> google.protobuf.Timestamp - 17, // 2: coinnews.v1.Comment.block_time:type_name -> google.protobuf.Timestamp - 0, // 3: coinnews.v1.ListFrontPageRequest.subtype:type_name -> coinnews.v1.Subtype - 1, // 4: coinnews.v1.ListFrontPageResponse.items:type_name -> coinnews.v1.Item - 0, // 5: coinnews.v1.ListNewFeedRequest.subtype:type_name -> coinnews.v1.Subtype - 1, // 6: coinnews.v1.ListNewFeedResponse.items:type_name -> coinnews.v1.Item - 1, // 7: coinnews.v1.GetItemResponse.item:type_name -> coinnews.v1.Item - 2, // 8: coinnews.v1.ListThreadResponse.comments:type_name -> coinnews.v1.Comment - 1, // 9: coinnews.v1.ListByAuthorResponse.items:type_name -> coinnews.v1.Item - 1, // 10: coinnews.v1.ListByTopicResponse.items:type_name -> coinnews.v1.Item - 3, // 11: coinnews.v1.ListTopicsResponse.topics:type_name -> coinnews.v1.Topic - 4, // 12: coinnews.v1.CoinNewsService.ListFrontPage:input_type -> coinnews.v1.ListFrontPageRequest - 6, // 13: coinnews.v1.CoinNewsService.ListNewFeed:input_type -> coinnews.v1.ListNewFeedRequest - 8, // 14: coinnews.v1.CoinNewsService.GetItem:input_type -> coinnews.v1.GetItemRequest - 10, // 15: coinnews.v1.CoinNewsService.ListThread:input_type -> coinnews.v1.ListThreadRequest - 12, // 16: coinnews.v1.CoinNewsService.ListByAuthor:input_type -> coinnews.v1.ListByAuthorRequest - 14, // 17: coinnews.v1.CoinNewsService.ListByTopic:input_type -> coinnews.v1.ListByTopicRequest - 18, // 18: coinnews.v1.CoinNewsService.ListTopics:input_type -> google.protobuf.Empty - 5, // 19: coinnews.v1.CoinNewsService.ListFrontPage:output_type -> coinnews.v1.ListFrontPageResponse - 7, // 20: coinnews.v1.CoinNewsService.ListNewFeed:output_type -> coinnews.v1.ListNewFeedResponse - 9, // 21: coinnews.v1.CoinNewsService.GetItem:output_type -> coinnews.v1.GetItemResponse - 11, // 22: coinnews.v1.CoinNewsService.ListThread:output_type -> coinnews.v1.ListThreadResponse - 13, // 23: coinnews.v1.CoinNewsService.ListByAuthor:output_type -> coinnews.v1.ListByAuthorResponse - 15, // 24: coinnews.v1.CoinNewsService.ListByTopic:output_type -> coinnews.v1.ListByTopicResponse - 16, // 25: coinnews.v1.CoinNewsService.ListTopics:output_type -> coinnews.v1.ListTopicsResponse - 19, // [19:26] is the sub-list for method output_type - 12, // [12:19] is the sub-list for method input_type - 12, // [12:12] is the sub-list for extension type_name - 12, // [12:12] is the sub-list for extension extendee - 0, // [0:12] is the sub-list for field type_name + 18, // 1: coinnews.v1.Item.block_time:type_name -> google.protobuf.Timestamp + 3, // 2: coinnews.v1.Item.reactions:type_name -> coinnews.v1.Reaction + 18, // 3: coinnews.v1.Comment.block_time:type_name -> google.protobuf.Timestamp + 3, // 4: coinnews.v1.Comment.reactions:type_name -> coinnews.v1.Reaction + 0, // 5: coinnews.v1.ListFrontPageRequest.subtype:type_name -> coinnews.v1.Subtype + 1, // 6: coinnews.v1.ListFrontPageResponse.items:type_name -> coinnews.v1.Item + 0, // 7: coinnews.v1.ListNewFeedRequest.subtype:type_name -> coinnews.v1.Subtype + 1, // 8: coinnews.v1.ListNewFeedResponse.items:type_name -> coinnews.v1.Item + 1, // 9: coinnews.v1.GetItemResponse.item:type_name -> coinnews.v1.Item + 2, // 10: coinnews.v1.ListThreadResponse.comments:type_name -> coinnews.v1.Comment + 1, // 11: coinnews.v1.ListByAuthorResponse.items:type_name -> coinnews.v1.Item + 1, // 12: coinnews.v1.ListByTopicResponse.items:type_name -> coinnews.v1.Item + 4, // 13: coinnews.v1.ListTopicsResponse.topics:type_name -> coinnews.v1.Topic + 5, // 14: coinnews.v1.CoinNewsService.ListFrontPage:input_type -> coinnews.v1.ListFrontPageRequest + 7, // 15: coinnews.v1.CoinNewsService.ListNewFeed:input_type -> coinnews.v1.ListNewFeedRequest + 9, // 16: coinnews.v1.CoinNewsService.GetItem:input_type -> coinnews.v1.GetItemRequest + 11, // 17: coinnews.v1.CoinNewsService.ListThread:input_type -> coinnews.v1.ListThreadRequest + 13, // 18: coinnews.v1.CoinNewsService.ListByAuthor:input_type -> coinnews.v1.ListByAuthorRequest + 15, // 19: coinnews.v1.CoinNewsService.ListByTopic:input_type -> coinnews.v1.ListByTopicRequest + 19, // 20: coinnews.v1.CoinNewsService.ListTopics:input_type -> google.protobuf.Empty + 6, // 21: coinnews.v1.CoinNewsService.ListFrontPage:output_type -> coinnews.v1.ListFrontPageResponse + 8, // 22: coinnews.v1.CoinNewsService.ListNewFeed:output_type -> coinnews.v1.ListNewFeedResponse + 10, // 23: coinnews.v1.CoinNewsService.GetItem:output_type -> coinnews.v1.GetItemResponse + 12, // 24: coinnews.v1.CoinNewsService.ListThread:output_type -> coinnews.v1.ListThreadResponse + 14, // 25: coinnews.v1.CoinNewsService.ListByAuthor:output_type -> coinnews.v1.ListByAuthorResponse + 16, // 26: coinnews.v1.CoinNewsService.ListByTopic:output_type -> coinnews.v1.ListByTopicResponse + 17, // 27: coinnews.v1.CoinNewsService.ListTopics:output_type -> coinnews.v1.ListTopicsResponse + 21, // [21:28] is the sub-list for method output_type + 14, // [14:21] is the sub-list for method input_type + 14, // [14:14] is the sub-list for extension type_name + 14, // [14:14] is the sub-list for extension extendee + 0, // [0:14] is the sub-list for field type_name } func init() { file_coinnews_v1_coinnews_proto_init() } @@ -1285,15 +1365,15 @@ func file_coinnews_v1_coinnews_proto_init() { if File_coinnews_v1_coinnews_proto != nil { return } - file_coinnews_v1_coinnews_proto_msgTypes[3].OneofWrappers = []any{} - file_coinnews_v1_coinnews_proto_msgTypes[5].OneofWrappers = []any{} + file_coinnews_v1_coinnews_proto_msgTypes[4].OneofWrappers = []any{} + file_coinnews_v1_coinnews_proto_msgTypes[6].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_coinnews_v1_coinnews_proto_rawDesc), len(file_coinnews_v1_coinnews_proto_rawDesc)), NumEnums: 1, - NumMessages: 16, + NumMessages: 17, NumExtensions: 0, NumServices: 1, }, diff --git a/coinnews/server/go.mod b/coinnews/server/go.mod index 76e6989d46..ac8ef7125e 100644 --- a/coinnews/server/go.mod +++ b/coinnews/server/go.mod @@ -7,6 +7,7 @@ require ( connectrpc.com/connect/v2 v2.0.2 connectrpc.com/grpcreflect/v2 v2.0.0 github.com/LayerTwo-Labs/sidesail/coinnews/codec v0.0.0 + github.com/btcsuite/btcd/btcec/v2 v2.3.6 github.com/mattn/go-sqlite3 v1.14.32 github.com/rs/zerolog v1.34.0 github.com/stretchr/testify v1.11.1 @@ -14,7 +15,6 @@ require ( ) require ( - github.com/btcsuite/btcd/btcec/v2 v2.3.6 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect diff --git a/coinnews/server/proto/coinnews/v1/coinnews.proto b/coinnews/server/proto/coinnews/v1/coinnews.proto index ca44ef7961..be31b050c2 100644 --- a/coinnews/server/proto/coinnews/v1/coinnews.proto +++ b/coinnews/server/proto/coinnews/v1/coinnews.proto @@ -63,6 +63,8 @@ message Item { uint32 vout = 16; // Fee of the transaction that carries the item, in sats. int64 fee_sats = 19; + // Reactions to the item, highest total first. + repeated Reaction reactions = 20; } message Comment { @@ -83,6 +85,15 @@ message Comment { uint32 vout = 13; // Fee of the transaction that carries the comment, in sats. int64 fee_sats = 14; + // Reactions to the comment, highest total first. + repeated Reaction reactions = 15; +} + +// The fee total of one emoji on an item. +message Reaction { + string emoji = 1; + // Sum of the fees of every reaction with this emoji, in sats. + int64 fee_sats = 2; } message Topic { diff --git a/coinnews/server/scanner/rules_test.go b/coinnews/server/scanner/rules_test.go new file mode 100644 index 0000000000..c048c125b7 --- /dev/null +++ b/coinnews/server/scanner/rules_test.go @@ -0,0 +1,184 @@ +package scanner + +import ( + "context" + "encoding/hex" + "fmt" + "slices" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + codec "github.com/LayerTwo-Labs/sidesail/coinnews/codec" + "github.com/LayerTwo-Labs/sidesail/coinnews/server/store" +) + +type board struct { + t *testing.T + s *Scanner + key *btcec.PrivateKey + next uint32 +} + +func newBoard(t *testing.T) *board { + t.Helper() + db, err := store.Open(context.Background(), t.TempDir()+"/coinnews.db") + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + return &board{t: t, s: &Scanner{DB: db, Log: zerolog.Nop()}, key: key} +} + +// post indexes payload in its own transaction of block 10 and returns its ItemID. +func (b *board) post(payload []byte, feeSats int64) codec.ItemID { + b.t.Helper() + b.next++ + txid := fmt.Sprintf("%064x", b.next) + pos := store.BlockPos{ + BlockHeight: 10, TxIndex: b.next, BlockTime: time.Unix(1_700_000_000, 0).UTC(), + TxID: txid, FeeSats: feeSats, + } + require.NoError(b.t, b.s.indexPayload(context.Background(), payload, pos)) + + raw, err := hex.DecodeString(txid) + require.NoError(b.t, err) + slices.Reverse(raw) + return codec.ComputeItemID([32]byte(raw), 0) +} + +func (b *board) story(headline, body string, feeSats int64) codec.ItemID { + b.t.Helper() + var tlvs []codec.TLV + if body != "" { + tlvs = append(tlvs, codec.TLV{Tag: codec.TLVBody, Value: []byte(body)}) + } + payload, err := codec.EncodeStory(codec.Story{Topic: codec.Topic{1, 2, 3, 4}, Headline: headline, TLVs: tlvs}) + require.NoError(b.t, err) + return b.post(payload, feeSats) +} + +func (b *board) comment(parent codec.ItemID, body string, feeSats int64) codec.ItemID { + b.t.Helper() + tlvs := []codec.TLV{{Tag: codec.TLVBody, Value: []byte(body)}} + blob, err := codec.SerialiseTLVs(tlvs) + require.NoError(b.t, err) + digest := codec.CommentSigHash(parent, blob) + sig, err := schnorr.Sign(b.key, digest[:]) + require.NoError(b.t, err) + c := codec.Comment{Parent: parent, TLVs: tlvs} + copy(c.AuthorXPK[:], schnorr.SerializePubKey(b.key.PubKey())) + copy(c.Sig[:], sig.Serialize()) + payload, err := codec.EncodeComment(c) + require.NoError(b.t, err) + return b.post(payload, feeSats) +} + +func (b *board) react(parent codec.ItemID, emoji string, feeSats int64) { + b.t.Helper() + payload, err := codec.EncodeReaction(codec.Reaction{Parent: parent, Emoji: emoji}) + require.NoError(b.t, err) + b.post(payload, feeSats) +} + +func (b *board) thread(root codec.ItemID) []string { + b.t.Helper() + rows, err := store.ListThread(context.Background(), b.s.DB, root) + require.NoError(b.t, err) + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = r.Body + } + return out +} + +func TestCommentRules(t *testing.T) { + t.Parallel() + + t.Run("a comment pays at least the story fee", func(t *testing.T) { + b := newBoard(t) + story := b.story("Twelve chars", "", 1000) + b.comment(story, "cheap", 999) + b.comment(story, "equal", 1000) + b.comment(story, "more", 5000) + assert.Equal(t, []string{"more", "equal"}, b.thread(story)) + }) + + t.Run("a comment holds no more characters than the headline and the body", func(t *testing.T) { + b := newBoard(t) + story := b.story("ab", "cd", 1000) + b.comment(story, "wxyz", 1000) + b.comment(story, "vwxyz", 1000) + b.comment(story, "👍👍👍👍", 1000) + assert.Equal(t, []string{"wxyz", "👍👍👍👍"}, b.thread(story)) + }) + + t.Run("a reply obeys the root story", func(t *testing.T) { + b := newBoard(t) + story := b.story("root story", "", 1000) + top := b.comment(story, "top", 4000) + b.comment(top, "cheap reply", 999) + b.comment(top, "reply", 1000) + assert.Equal(t, []string{"top", "reply"}, b.thread(story)) + }) + + t.Run("a reply to a dropped comment is dropped", func(t *testing.T) { + b := newBoard(t) + story := b.story("root story", "", 1000) + dropped := b.comment(story, "cheap", 1) + b.comment(dropped, "reply", 5000) + assert.Empty(t, b.thread(story)) + }) +} + +func TestContinuationOfACommentIsDropped(t *testing.T) { + t.Parallel() + ctx := context.Background() + b := newBoard(t) + story := b.story("root story", "", 1000) + comment := b.comment(story, "short", 1000) + + for i, head := range []codec.ItemID{story, comment} { + payload, err := codec.EncodeContinuation(codec.Continuation{Head: head, Seq: byte(i), Chunk: []byte("more")}) + require.NoError(t, err) + b.post(payload, 1000) + } + + var heads [][]byte + rows, err := b.s.DB.QueryContext(ctx, `SELECT head_id FROM cn_continuations`) + require.NoError(t, err) + defer rows.Close() //nolint:errcheck + for rows.Next() { + var h []byte + require.NoError(t, rows.Scan(&h)) + heads = append(heads, h) + } + require.NoError(t, rows.Err()) + assert.Equal(t, [][]byte{story[:]}, heads) +} + +func TestReactions(t *testing.T) { + t.Parallel() + ctx := context.Background() + b := newBoard(t) + story := b.story("root story", "", 1000) + b.react(story, "👍", 3513) + b.react(story, "👎", 617) + b.react(story, "💯", 398) + b.react(story, "👎", 8000) + b.react(codec.ItemID{0xff}, "👍", 9999) + + got, err := store.ListReactions(ctx, b.s.DB, []codec.ItemID{story}) + require.NoError(t, err) + assert.Equal(t, []store.Reaction{ + {Emoji: "👎", FeeSats: 8617}, + {Emoji: "👍", FeeSats: 3513}, + {Emoji: "💯", FeeSats: 398}, + }, got[story]) + assert.Len(t, got, 1, "a reaction to an unknown item is dropped") +} diff --git a/coinnews/server/scanner/scanner.go b/coinnews/server/scanner/scanner.go index 945c02968a..6f5b8f6935 100644 --- a/coinnews/server/scanner/scanner.go +++ b/coinnews/server/scanner/scanner.go @@ -171,9 +171,7 @@ func (s *Scanner) indexHeight(ctx context.Context, height uint32, prev [32]byte) } // indexPayload classifies one OP_RETURN payload and persists it. -// Mirrors bitwindow's engine hook: signature verification gates -// persistence, malformed and non-CoinNews payloads are dropped -// silently. +// Malformed payloads, and Messages that break spec §7–§9, are dropped. func (s *Scanner) indexPayload(ctx context.Context, data []byte, pos store.BlockPos) error { tag, msg, err := codec.DecodeMessage(data) if err != nil { @@ -184,14 +182,64 @@ func (s *Scanner) indexPayload(ctx context.Context, data []byte, pos store.Block Msg("coinnews-scanner: malformed payload, dropping") return nil } + reason, err := dropReason(ctx, s.DB, msg, pos) + if err != nil { + return err + } + if reason != "" { + s.Log.Debug().Str("txid", pos.TxID).Uint32("vout", pos.VoutIndex).Str("reason", reason). + Msg("coinnews-scanner: dropping message") + return nil + } + return store.Index(ctx, s.DB, store.IndexEnv{Pos: pos, TypeTag: tag, Msg: msg, Payload: data}) +} + +// dropReason returns why msg at pos breaks spec §7–§9, or "" when it obeys them. +func dropReason(ctx context.Context, db *sql.DB, msg any, pos store.BlockPos) (string, error) { switch m := msg.(type) { case *codec.Comment: if err := codec.VerifyComment(m); err != nil { - s.Log.Debug().Err(err).Str("txid", pos.TxID).Msg("coinnews-scanner: comment sig invalid") - return nil + return "comment signature invalid", nil + } + parent, ok, err := store.ResolveItem(ctx, db, m.Parent) + if err != nil { + return "", err + } + if !ok || !parent.Before(pos) { + return "comment parent unresolvable", nil + } + story, ok, err := store.RootStory(ctx, db, m.Parent) + if err != nil { + return "", err + } + if !ok { + return "comment has no root story", nil + } + var body string + if t := codec.FindFirst(m.TLVs, codec.TLVBody); t != nil { + body = string(t.Value) + } + if err := codec.CheckComment(story, pos.FeeSats, body); err != nil { + return err.Error(), nil + } + case *codec.Continuation: + head, ok, err := store.ResolveItem(ctx, db, m.Head) + if err != nil { + return "", err + } + if !ok || head.TypeTag != codec.TypeStory || head.BlockHeight != pos.BlockHeight || !head.Before(pos) { + return "continuation head is not an earlier story in the block", nil + } + case *codec.Reaction: + parent, ok, err := store.ResolveItem(ctx, db, m.Parent) + if err != nil { + return "", err + } + if !ok || !parent.Before(pos) { + return "reaction parent unresolvable", nil } } - return store.Index(ctx, s.DB, store.IndexEnv{Pos: pos, TypeTag: tag, Msg: msg, Payload: data}) + return "", nil } // opReturnPayload extracts the data bytes pushed by a single-push diff --git a/coinnews/server/store/query.go b/coinnews/server/store/query.go index c7d9bf91c5..28d96e9b05 100644 --- a/coinnews/server/store/query.go +++ b/coinnews/server/store/query.go @@ -5,6 +5,7 @@ import ( "database/sql" "fmt" "sort" + "strings" "time" codec "github.com/LayerTwo-Labs/sidesail/coinnews/codec" @@ -280,3 +281,47 @@ func nullableSubtype(s *codec.Subtype) any { } return byte(*s) } + +// Reaction is the fee total of one emoji on an Item (spec §8). +type Reaction struct { + Emoji string + FeeSats int64 +} + +// ListReactions returns the reactions of each Item in ids, highest total first. +func ListReactions(ctx context.Context, db *sql.DB, ids []codec.ItemID) (map[codec.ItemID][]Reaction, error) { + out := map[codec.ItemID][]Reaction{} + if len(ids) == 0 { + return out, nil + } + args := make([]any, len(ids)) + for i, id := range ids { + args[i] = id[:] + } + rows, err := db.QueryContext(ctx, ` + SELECT r.parent_id, r.emoji, SUM(i.fee_sats) AS total + FROM cn_reactions r + JOIN cn_items i ON i.item_id = r.item_id + WHERE r.parent_id IN (?`+strings.Repeat(",?", len(ids)-1)+`) + GROUP BY r.parent_id, r.emoji + ORDER BY total DESC, r.emoji ASC + `, args...) + if err != nil { + return nil, fmt.Errorf("ListReactions: %w", err) + } + defer rows.Close() //nolint:errcheck + + for rows.Next() { + var ( + parent []byte + r Reaction + ) + if err := rows.Scan(&parent, &r.Emoji, &r.FeeSats); err != nil { + return nil, err + } + var id codec.ItemID + copy(id[:], parent) + out[id] = append(out[id], r) + } + return out, rows.Err() +} diff --git a/coinnews/server/store/schema.sql b/coinnews/server/store/schema.sql index 8467e80518..06ce902f36 100644 --- a/coinnews/server/store/schema.sql +++ b/coinnews/server/store/schema.sql @@ -60,6 +60,13 @@ CREATE TABLE IF NOT EXISTS cn_continuations ( PRIMARY KEY (head_id, seq) ); +CREATE TABLE IF NOT EXISTS cn_reactions ( + item_id BLOB(12) PRIMARY KEY REFERENCES cn_items(item_id), + parent_id BLOB(12) NOT NULL, + emoji TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_cn_reactions_parent ON cn_reactions (parent_id); + -- Scanner cursor: highest block we've ingested. Used so we don't -- rescan the whole chain on every restart. CREATE TABLE IF NOT EXISTS cn_scanner_cursor ( diff --git a/coinnews/server/store/store.go b/coinnews/server/store/store.go index 5e039f8156..9ebd2d411b 100644 --- a/coinnews/server/store/store.go +++ b/coinnews/server/store/store.go @@ -9,6 +9,7 @@ import ( "database/sql" _ "embed" "encoding/hex" + "errors" "fmt" "slices" "strings" @@ -21,56 +22,52 @@ import ( //go:embed schema.sql var schemaSQL string -// Open opens (or creates) the SQLite database at `path`, applies -// the schema if missing, and returns a ready *sql.DB. Safe to call -// repeatedly — `CREATE TABLE IF NOT EXISTS` makes the schema apply -// idempotent. +// indexVersion changes each time the rules of what the index accepts change. +// An index from an older version is dropped, and the scanner reads every block again. +const indexVersion = 1 + +// Open opens (or creates) the SQLite database at `path` and applies the schema. func Open(ctx context.Context, path string) (*sql.DB, error) { db, err := sql.Open("sqlite3", path+"?_journal=WAL&_busy_timeout=5000&_foreign_keys=on") if err != nil { return nil, fmt.Errorf("open sqlite: %w", err) } + if err := dropOldIndex(ctx, db); err != nil { + _ = db.Close() + return nil, err + } if _, err := db.ExecContext(ctx, schemaSQL); err != nil { _ = db.Close() return nil, fmt.Errorf("apply schema: %w", err) } - if err := addFeeColumn(ctx, db); err != nil { + if _, err := db.ExecContext(ctx, fmt.Sprintf(`PRAGMA user_version = %d`, indexVersion)); err != nil { _ = db.Close() - return nil, err + return nil, fmt.Errorf("set index version: %w", err) } return db, nil } -// addFeeColumn upgrades an index from before fee_sats. It clears the index -// and the cursor, so the scanner reads every block again and fills in each fee. -func addFeeColumn(ctx context.Context, db *sql.DB) error { - var found int - if err := db.QueryRowContext(ctx, - `SELECT COUNT(*) FROM pragma_table_info('cn_items') WHERE name = 'fee_sats'`).Scan(&found); err != nil { - return fmt.Errorf("read cn_items columns: %w", err) +func dropOldIndex(ctx context.Context, db *sql.DB) error { + var version int + if err := db.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&version); err != nil { + return fmt.Errorf("read index version: %w", err) } - if found > 0 { + if version >= indexVersion { return nil } tx, err := db.BeginTx(ctx, nil) if err != nil { - return fmt.Errorf("add fee column: begin tx: %w", err) + return fmt.Errorf("drop old index: begin tx: %w", err) } defer tx.Rollback() //nolint:errcheck // committed on success path - for _, stmt := range []string{ - `DROP TABLE IF EXISTS cn_votes`, - `DELETE FROM cn_stories`, - `DELETE FROM cn_comments`, - `DELETE FROM cn_continuations`, - `DELETE FROM cn_topics`, - `DELETE FROM cn_items`, - `DELETE FROM cn_scanner_cursor`, - `ALTER TABLE cn_items ADD COLUMN fee_sats INTEGER NOT NULL DEFAULT 0`, + for _, table := range []string{ + "cn_votes", "cn_reactions", "cn_stories", "cn_comments", "cn_continuations", + "cn_topics", "cn_items", "cn_scanner_cursor", } { - if _, err := tx.ExecContext(ctx, stmt); err != nil { - return fmt.Errorf("add fee column: %s: %w", stmt, err) + if _, err := tx.ExecContext(ctx, `DROP TABLE IF EXISTS `+table); err != nil { + return fmt.Errorf("drop old index: %s: %w", table, err) } } return tx.Commit() @@ -92,12 +89,12 @@ type BlockPos struct { type IndexEnv struct { Pos BlockPos TypeTag codec.TypeTag - Msg any // *codec.TopicCreation | *codec.Story | *codec.Comment | *codec.Continuation + Msg any // *codec.TopicCreation | *codec.Story | *codec.Comment | *codec.Continuation | *codec.Reaction Payload []byte // the raw OP_RETURN bytes Msg was decoded from } // Index dispatches one decoded CoinNews Message into the right table(s). -// Caller MUST have already verified Comment signatures. +// Caller MUST have already checked the Message against spec §7–§9. func Index(ctx context.Context, db *sql.DB, env IndexEnv) error { tx, err := db.BeginTx(ctx, nil) if err != nil { @@ -127,6 +124,12 @@ func Index(ctx context.Context, db *sql.DB, env IndexEnv) error { if err := indexContinuation(ctx, tx, env.Pos, m); err != nil { return err } + case *codec.Reaction: + if _, err := tx.ExecContext(ctx, ` + INSERT OR IGNORE INTO cn_reactions (item_id, parent_id, emoji) VALUES (?, ?, ?) + `, itemID[:], m.Parent[:], m.Emoji); err != nil { + return fmt.Errorf("coinnews: insert cn_reactions: %w", err) + } default: return fmt.Errorf("coinnews: unhandled message type %T", env.Msg) } @@ -225,6 +228,64 @@ func indexContinuation(ctx context.Context, tx *sql.Tx, pos BlockPos, c *codec.C return nil } +// ItemRef is the scan position and type of an indexed Item. +type ItemRef struct { + BlockHeight uint32 + TxIndex uint32 + VoutIndex uint32 + TypeTag codec.TypeTag +} + +// Before reports whether the Item comes before pos in scan order (spec §4.2). +func (r ItemRef) Before(pos BlockPos) bool { + if r.BlockHeight != pos.BlockHeight { + return r.BlockHeight < pos.BlockHeight + } + if r.TxIndex != pos.TxIndex { + return r.TxIndex < pos.TxIndex + } + return r.VoutIndex < pos.VoutIndex +} + +// ResolveItem returns the Item with this ItemID, false when the index has none. +func ResolveItem(ctx context.Context, db *sql.DB, id codec.ItemID) (ItemRef, bool, error) { + var ref ItemRef + err := db.QueryRowContext(ctx, ` + SELECT block_height, tx_index, vout_index, type_tag FROM cn_items WHERE item_id = ? + `, id[:]).Scan(&ref.BlockHeight, &ref.TxIndex, &ref.VoutIndex, &ref.TypeTag) + switch { + case errors.Is(err, sql.ErrNoRows): + return ItemRef{}, false, nil + case err != nil: + return ItemRef{}, false, fmt.Errorf("coinnews: resolve item: %w", err) + } + return ref, true, nil +} + +// RootStory walks up the comment chain from id to its Story (spec §7.1). +// It returns false when the chain ends at no Story. +func RootStory(ctx context.Context, db *sql.DB, id codec.ItemID) (codec.StoryRules, bool, error) { + var story codec.StoryRules + err := db.QueryRowContext(ctx, ` + WITH RECURSIVE up(id) AS ( + SELECT ? + UNION ALL + SELECT c.parent_id FROM cn_comments c JOIN up ON c.item_id = up.id + ) + SELECT i.fee_sats, s.headline, COALESCE(s.body, '') + FROM up + JOIN cn_stories s ON s.item_id = up.id + JOIN cn_items i ON i.item_id = s.item_id + `, id[:]).Scan(&story.FeeSats, &story.Headline, &story.Body) + switch { + case errors.Is(err, sql.ErrNoRows): + return codec.StoryRules{}, false, nil + case err != nil: + return codec.StoryRules{}, false, fmt.Errorf("coinnews: root story: %w", err) + } + return story, true, nil +} + // PurgeAtOrAbove deletes every cn_* row originating from a block at // or above `fromHeight`. Called on reorg detection before replay. func PurgeAtOrAbove(ctx context.Context, db *sql.DB, fromHeight uint32) error { @@ -237,6 +298,7 @@ func PurgeAtOrAbove(ctx context.Context, db *sql.DB, fromHeight uint32) error { for _, q := range []string{ `DELETE FROM cn_stories WHERE item_id IN (SELECT item_id FROM cn_items WHERE block_height >= ?)`, `DELETE FROM cn_comments WHERE item_id IN (SELECT item_id FROM cn_items WHERE block_height >= ?)`, + `DELETE FROM cn_reactions WHERE item_id IN (SELECT item_id FROM cn_items WHERE block_height >= ?)`, `DELETE FROM cn_continuations WHERE block_height >= ?`, `DELETE FROM cn_topics WHERE created_height >= ?`, `DELETE FROM cn_items WHERE block_height >= ?`, diff --git a/coinnews/server/store/store_test.go b/coinnews/server/store/store_test.go index ae2d5aefb8..a867a2a225 100644 --- a/coinnews/server/store/store_test.go +++ b/coinnews/server/store/store_test.go @@ -155,7 +155,7 @@ func TestOpReturnPayload_RoundTrip(t *testing.T) { require.IsType(t, &codec.Story{}, msg) } -func TestOpen_AddsFeeColumnToOldIndex(t *testing.T) { +func TestOpen_DropsOldIndex(t *testing.T) { t.Parallel() ctx := context.Background() path := t.TempDir() + "/coinnews.db" @@ -173,7 +173,8 @@ func TestOpen_AddsFeeColumnToOldIndex(t *testing.T) { require.NoError(t, err) _, err = raw.ExecContext(ctx, ` ALTER TABLE cn_items DROP COLUMN fee_sats; - CREATE TABLE cn_votes (target_id BLOB NOT NULL, author_xpk BLOB NOT NULL)`) + CREATE TABLE cn_votes (target_id BLOB NOT NULL, author_xpk BLOB NOT NULL); + PRAGMA user_version = 0`) require.NoError(t, err) require.NoError(t, raw.Close()) @@ -183,7 +184,7 @@ func TestOpen_AddsFeeColumnToOldIndex(t *testing.T) { var items, votes int require.NoError(t, db.QueryRowContext(ctx, `SELECT COUNT(*) FROM cn_items`).Scan(&items)) - assert.Zero(t, items, "the old index is cleared so the scanner fills in every fee") + assert.Zero(t, items, "the scanner reads every block again under the current rules") require.NoError(t, db.QueryRowContext(ctx, `SELECT COUNT(*) FROM sqlite_master WHERE name = 'cn_votes'`).Scan(&votes)) assert.Zero(t, votes) diff --git a/docs/coinnews-protocol.md b/docs/coinnews-protocol.md index 9afb5789af..7a33c2b1e4 100644 --- a/docs/coinnews-protocol.md +++ b/docs/coinnews-protocol.md @@ -44,9 +44,10 @@ ignored — they're reserved for future versions. | `0x01` | Topic Creation | 5 | | `0x02` | Story | 6 | | `0x03` | Comment | 7 | -| `0x04` | Retired (Upvote) | 8 | -| `0x05` | Retired (Downvote) | 8 | +| `0x04` | Retired (Upvote) | — | +| `0x05` | Retired (Downvote) | — | | `0x06` | Continuation | 9 | +| `0x07` | Reaction | 8 | | `0x80…` | Application use | — | ### 2. Varint length @@ -76,7 +77,7 @@ topic from its parent Item. ### 4. Item identifiers References to other Items (a Comment's parent, a Continuation's -head) use **ItemID**: +head, a Reaction's parent) use **ItemID**: ``` ItemID = sha256(txid_LE(32) ‖ vout_LE(4))[0:12] @@ -161,7 +162,7 @@ are normative; any deviation is a non-conformant implementation. every Item that exists in their shared range. * **Determinism budget.** Given a chain tip, the canonical output of an indexer is the tuple - `(items_by_id, topics_by_id)`. + `(items_by_id, topics_by_id, reaction_totals)`. Conforming indexers MUST agree byte-for-byte on this tuple modulo serialisation. Anything beyond it (rendered HTML, sort caches, search indexes) is implementation-defined. @@ -210,10 +211,37 @@ non-empty body MUST be carried in TLV; long bodies chunk via §9. Indexers MUST drop Comments whose `parent_id` is unresolvable in the index, or whose signature fails to verify. -### 8. Vote (retired) +#### 7.1 Comment rules -TypeTags `0x04` and `0x05` carried up and down votes. They are -retired. Indexers MUST drop them like any unknown TypeTag (§1). +The **root Story** of a Comment is the Story at the top of its parent +chain. Indexers MUST drop a Comment that breaks either rule: + +1. `fee_sats` (§13) of the Comment is less than `fee_sats` of the root + Story. +2. The Comment's `body` holds more characters than the root Story's + `headline` and `body` together. + +`body` is the first `body` TLV (§10) of the Message's own payload; +Continuation chunks do not count. A character is one Unicode code +point, after each invalid UTF-8 byte is replaced with U+FFFD. A +Comment whose parent was dropped is unresolvable, so the rules hold +for each reply in a thread. + +### 8. Reaction + +``` +"CN" ‖ 0x07 ‖ parent_id(12) ‖ emoji(varint+UTF-8) +``` + +`emoji` is 1–32 bytes of valid UTF-8, with no trailing bytes. +Reactions are unsigned. Indexers MUST drop a Reaction whose +`parent_id` is unresolvable, or that is not after its parent in scan +order (§4.2). + +The total of an emoji on an Item is the sum of `fee_sats` (§13) of +each Reaction with that `parent_id` and that exact `emoji`. Anyone can +add to a total. TypeTags `0x04` and `0x05` carried up and down votes; +they are retired, and indexers drop them like any unknown TypeTag (§1). ### 9. Continuation @@ -223,7 +251,8 @@ retired. Indexers MUST drop them like any unknown TypeTag (§1). `seq` is 0-indexed and monotonically increasing. Continuations MUST appear in the head's transaction or a later transaction in the same -block, in `seq` order. The reassembled trailing TLV section MUST NOT +block, in `seq` order. The head MUST be a Story; a Continuation of +any other Item is dropped. The reassembled trailing TLV section MUST NOT exceed 8 KiB. Out-of-order, gapped, or post-block continuations ⇒ drop the message. @@ -307,7 +336,8 @@ fee_sats DESC, block_height DESC, tx_index DESC, vout_index DESC ``` A comment thread orders siblings by `fee_sats DESC`, then canonical -scan order (§4.2) ascending. +scan order (§4.2) ascending. The reactions of an Item order by total +DESC, then emoji bytes ascending. ### 14. Retention & fees @@ -341,12 +371,15 @@ surface the per-message fee in the publish flow. them lets new fields ship at client cadence. * **Fee ranking, no votes.** A paid Item with few votes looks rejected. The fee is the only rank signal, so every paid Item - stays visible. + stays visible. A Reaction counts sats, not people. +* **Comments pay at least the Story.** A cheap reply cannot bury a + paid Story, and a reply cannot hold more text than the Story it + answers. ## Reference Implementation -The Go codec at `bitwindow/server/coinnews/` covers all four message -types, the TLV layer, ItemID truncation, and BIP-340 Schnorr verify +The Go codec at `coinnews/codec/` covers all five message +types, the §7.1 comment rules, the TLV layer, ItemID truncation, and BIP-340 Schnorr verify with per-type tagged hashes. ## Test Vectors @@ -358,6 +391,13 @@ hex: 434e0148 4e53211e 0b48 6163 6b65 7220 4e65 7773 total: 18 B ``` +``` +# Reaction: 👍 on ItemID 0102030405060708090a0b0c +"CN" ‖ 07 ‖ 0102030405060708090a0b0c ‖ 04 f09f918d +hex: 434e0701 02030405 06070809 0a0b0c04 f09f918d +total: 20 B +``` + ``` # Story: link post in topic 0x484e5321 # headline = "Microsoft and OpenAI end revenue-sharing deal" (45 B) diff --git a/photon/pubspec.yaml b/photon/pubspec.yaml index 0b2b01226e..6ccf300a02 100644 --- a/photon/pubspec.yaml +++ b/photon/pubspec.yaml @@ -2,7 +2,7 @@ name: photon description: UI for Drivechain (BIP300/301) based sidechains publish_to: "none" # Remove this line if you wish to publish to pub.dev -version: 1.0.269 +version: 1.0.270 environment: sdk: 3.13.7 diff --git a/sidechain_core/lib/gen/misc/v1/misc.connect.client.dart b/sidechain_core/lib/gen/misc/v1/misc.connect.client.dart index 13d5a320ca..e35a1c3c0f 100644 --- a/sidechain_core/lib/gen/misc/v1/misc.connect.client.dart +++ b/sidechain_core/lib/gen/misc/v1/misc.connect.client.dart @@ -171,6 +171,24 @@ extension type MiscServiceClient(connect.Transport _transport) { ); } + /// Broadcasts a Reaction (CoinNews Reaction, 0x07) on an Item. + Future reactNews( + miscv1misc.ReactNewsRequest input, { + connect.Headers? headers, + connect.AbortSignal? signal, + Function(connect.Headers)? onHeader, + Function(connect.Headers)? onTrailer, + }) { + return connect.Client(_transport).unary( + specs.MiscService.reactNews, + input, + signal: signal, + headers: headers, + onHeader: onHeader, + onTrailer: onTrailer, + ); + } + /// The fee that the active wallet pays for a story, a comment or a topic with no fee /// choice. Broadcasts nothing. Future estimateNewsFee( diff --git a/sidechain_core/lib/gen/misc/v1/misc.connect.spec.dart b/sidechain_core/lib/gen/misc/v1/misc.connect.spec.dart index 9c0ab65d47..c2539a9116 100644 --- a/sidechain_core/lib/gen/misc/v1/misc.connect.spec.dart +++ b/sidechain_core/lib/gen/misc/v1/misc.connect.spec.dart @@ -83,6 +83,14 @@ abstract final class MiscService { miscv1misc.ListCommentsResponse.new, ); + /// Broadcasts a Reaction (CoinNews Reaction, 0x07) on an Item. + static const reactNews = connect.Spec( + '/$name/ReactNews', + connect.StreamType.unary, + miscv1misc.ReactNewsRequest.new, + miscv1misc.ReactNewsResponse.new, + ); + /// The fee that the active wallet pays for a story, a comment or a topic with no fee /// choice. Broadcasts nothing. static const estimateNewsFee = connect.Spec( diff --git a/sidechain_core/lib/gen/misc/v1/misc.pb.dart b/sidechain_core/lib/gen/misc/v1/misc.pb.dart index d5b48574f4..f0ce04de32 100644 --- a/sidechain_core/lib/gen/misc/v1/misc.pb.dart +++ b/sidechain_core/lib/gen/misc/v1/misc.pb.dart @@ -913,6 +913,7 @@ class EstimateNewsFeeRequest extends $pb.GeneratedMessage { $core.bool? nsfw, $core.String? topicName, $core.int? retentionDays, + $core.String? emoji, }) { final result = EstimateNewsFeeRequest._(); if (action != null) result.action = action; @@ -924,6 +925,7 @@ class EstimateNewsFeeRequest extends $pb.GeneratedMessage { if (nsfw != null) result.nsfw = nsfw; if (topicName != null) result.topicName = topicName; if (retentionDays != null) result.retentionDays = retentionDays; + if (emoji != null) result.emoji = emoji; return result; } @@ -948,6 +950,7 @@ class EstimateNewsFeeRequest extends $pb.GeneratedMessage { ..aOB(7, _omitFieldNames ? '' : 'nsfw') ..aOS(8, _omitFieldNames ? '' : 'topicName') ..aI(9, _omitFieldNames ? '' : 'retentionDays') + ..aOS(10, _omitFieldNames ? '' : 'emoji') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') @@ -1053,6 +1056,16 @@ class EstimateNewsFeeRequest extends $pb.GeneratedMessage { $core.bool hasRetentionDays() => $_has(8); @$pb.TagNumber(9) void clearRetentionDays() => $_clearField(9); + + /// Reaction field that changes the size of the payload. + @$pb.TagNumber(10) + $core.String get emoji => $_getSZ(9); + @$pb.TagNumber(10) + set emoji($core.String value) => $_setString(9, value); + @$pb.TagNumber(10) + $core.bool hasEmoji() => $_has(9); + @$pb.TagNumber(10) + void clearEmoji() => $_clearField(10); } class EstimateNewsFeeResponse extends $pb.GeneratedMessage { @@ -1204,6 +1217,8 @@ class CoinNews extends $pb.GeneratedMessage { $core.int? vout, $core.bool? outdated, $core.bool? pending, + $core.Iterable? reactions, + $core.int? maxCommentChars, }) { final result = CoinNews._(); if (id != null) result.id = id; @@ -1220,6 +1235,8 @@ class CoinNews extends $pb.GeneratedMessage { if (vout != null) result.vout = vout; if (outdated != null) result.outdated = outdated; if (pending != null) result.pending = pending; + if (reactions != null) result.reactions.addAll(reactions); + if (maxCommentChars != null) result.maxCommentChars = maxCommentChars; return result; } @@ -1247,6 +1264,8 @@ class CoinNews extends $pb.GeneratedMessage { ..aI(15, _omitFieldNames ? '' : 'vout', fieldType: $pb.PbFieldType.OU3) ..aOB(16, _omitFieldNames ? '' : 'outdated') ..aOB(17, _omitFieldNames ? '' : 'pending') + ..pPM(18, _omitFieldNames ? '' : 'reactions', subBuilder: Reaction.$_createMessage) + ..aI(19, _omitFieldNames ? '' : 'maxCommentChars') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') @@ -1404,6 +1423,86 @@ class CoinNews extends $pb.GeneratedMessage { $core.bool hasPending() => $_has(13); @$pb.TagNumber(17) void clearPending() => $_clearField(17); + + /// Reactions to the story, highest total first. + @$pb.TagNumber(18) + $pb.PbList get reactions => $_getList(14); + + /// The most characters a comment on this story can hold (spec §7.1). + @$pb.TagNumber(19) + $core.int get maxCommentChars => $_getIZ(15); + @$pb.TagNumber(19) + set maxCommentChars($core.int value) => $_setSignedInt32(15, value); + @$pb.TagNumber(19) + $core.bool hasMaxCommentChars() => $_has(15); + @$pb.TagNumber(19) + void clearMaxCommentChars() => $_clearField(19); +} + +/// The fee total of one emoji on an item. +class Reaction extends $pb.GeneratedMessage { + factory Reaction({ + $core.String? emoji, + $fixnum.Int64? feeSats, + }) { + final result = Reaction._(); + if (emoji != null) result.emoji = emoji; + if (feeSats != null) result.feeSats = feeSats; + return result; + } + + Reaction._(); + + factory Reaction.fromBuffer($core.List<$core.int> data, + [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => + Reaction()..mergeFromBuffer(data, registry); + factory Reaction.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => + Reaction()..mergeFromJson(json, registry); + + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Reaction', + package: const $pb.PackageName(_omitMessageNames ? '' : 'misc.v1'), createEmptyInstance: Reaction.$_createMessage) + ..aOS(1, _omitFieldNames ? '' : 'emoji') + ..aInt64(2, _omitFieldNames ? '' : 'feeSats') + ..hasRequiredFields = false; + + @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') + Reaction clone() => deepCopy(); + @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') + Reaction copyWith(void Function(Reaction) updates) => + super.copyWith((message) => updates(message as Reaction)) as Reaction; + + @$core.override + $pb.BuilderInfo get info_ => _i; + + @$core.pragma('dart2js:noInline') + @$core.Deprecated('Use Reaction() / Reaction.new instead') + static Reaction create() => Reaction._(); + static $pb.GeneratedMessage $_createMessage() => Reaction._(); + @$core.override + Reaction createEmptyInstance() => Reaction._(); + @$core.pragma('dart2js:noInline') + static Reaction getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(Reaction.$_createMessage); + static Reaction? _defaultInstance; + + @$pb.TagNumber(1) + $core.String get emoji => $_getSZ(0); + @$pb.TagNumber(1) + set emoji($core.String value) => $_setString(0, value); + @$pb.TagNumber(1) + $core.bool hasEmoji() => $_has(0); + @$pb.TagNumber(1) + void clearEmoji() => $_clearField(1); + + /// Sum of the fees of every reaction with this emoji. + @$pb.TagNumber(2) + $fixnum.Int64 get feeSats => $_getI64(1); + @$pb.TagNumber(2) + set feeSats($fixnum.Int64 value) => $_setInt64(1, value); + @$pb.TagNumber(2) + $core.bool hasFeeSats() => $_has(1); + @$pb.TagNumber(2) + void clearFeeSats() => $_clearField(2); } class ListCoinNewsResponse extends $pb.GeneratedMessage { @@ -1474,7 +1573,6 @@ class CommentNewsRequest extends $pb.GeneratedMessage { $core.String? url, $core.String? lang, $core.String? replyQuote, - $fixnum.Int64? feeSatPerVbyte, $fixnum.Int64? feeSats, }) { final result = CommentNewsRequest._(); @@ -1483,7 +1581,6 @@ class CommentNewsRequest extends $pb.GeneratedMessage { if (url != null) result.url = url; if (lang != null) result.lang = lang; if (replyQuote != null) result.replyQuote = replyQuote; - if (feeSatPerVbyte != null) result.feeSatPerVbyte = feeSatPerVbyte; if (feeSats != null) result.feeSats = feeSats; return result; } @@ -1505,8 +1602,6 @@ class CommentNewsRequest extends $pb.GeneratedMessage { ..aOS(3, _omitFieldNames ? '' : 'url') ..aOS(4, _omitFieldNames ? '' : 'lang') ..aOS(5, _omitFieldNames ? '' : 'replyQuote') - ..a<$fixnum.Int64>(6, _omitFieldNames ? '' : 'feeSatPerVbyte', $pb.PbFieldType.OU6, - defaultOrMaker: $fixnum.Int64.ZERO) ..a<$fixnum.Int64>(7, _omitFieldNames ? '' : 'feeSats', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) ..hasRequiredFields = false; @@ -1577,22 +1672,13 @@ class CommentNewsRequest extends $pb.GeneratedMessage { @$pb.TagNumber(5) void clearReplyQuote() => $_clearField(5); - /// Fee options - exactly one should be set (0 = use Core's estimate) - @$pb.TagNumber(6) - $fixnum.Int64 get feeSatPerVbyte => $_getI64(5); - @$pb.TagNumber(6) - set feeSatPerVbyte($fixnum.Int64 value) => $_setInt64(5, value); - @$pb.TagNumber(6) - $core.bool hasFeeSatPerVbyte() => $_has(5); - @$pb.TagNumber(6) - void clearFeeSatPerVbyte() => $_clearField(6); - + /// Fee of the comment. It must be at least the fee of the root story (spec §7.1). @$pb.TagNumber(7) - $fixnum.Int64 get feeSats => $_getI64(6); + $fixnum.Int64 get feeSats => $_getI64(5); @$pb.TagNumber(7) - set feeSats($fixnum.Int64 value) => $_setInt64(6, value); + set feeSats($fixnum.Int64 value) => $_setInt64(5, value); @$pb.TagNumber(7) - $core.bool hasFeeSats() => $_has(6); + $core.bool hasFeeSats() => $_has(5); @$pb.TagNumber(7) void clearFeeSats() => $_clearField(7); } @@ -1651,6 +1737,140 @@ class CommentNewsResponse extends $pb.GeneratedMessage { void clearTxid() => $_clearField(1); } +class ReactNewsRequest extends $pb.GeneratedMessage { + factory ReactNewsRequest({ + $core.String? parentId, + $core.String? emoji, + $fixnum.Int64? feeSats, + }) { + final result = ReactNewsRequest._(); + if (parentId != null) result.parentId = parentId; + if (emoji != null) result.emoji = emoji; + if (feeSats != null) result.feeSats = feeSats; + return result; + } + + ReactNewsRequest._(); + + factory ReactNewsRequest.fromBuffer($core.List<$core.int> data, + [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => + ReactNewsRequest()..mergeFromBuffer(data, registry); + factory ReactNewsRequest.fromJson($core.String json, + [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => + ReactNewsRequest()..mergeFromJson(json, registry); + + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ReactNewsRequest', + package: const $pb.PackageName(_omitMessageNames ? '' : 'misc.v1'), + createEmptyInstance: ReactNewsRequest.$_createMessage) + ..aOS(1, _omitFieldNames ? '' : 'parentId') + ..aOS(2, _omitFieldNames ? '' : 'emoji') + ..a<$fixnum.Int64>(3, _omitFieldNames ? '' : 'feeSats', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) + ..hasRequiredFields = false; + + @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') + ReactNewsRequest clone() => deepCopy(); + @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') + ReactNewsRequest copyWith(void Function(ReactNewsRequest) updates) => + super.copyWith((message) => updates(message as ReactNewsRequest)) as ReactNewsRequest; + + @$core.override + $pb.BuilderInfo get info_ => _i; + + @$core.pragma('dart2js:noInline') + @$core.Deprecated('Use ReactNewsRequest() / ReactNewsRequest.new instead') + static ReactNewsRequest create() => ReactNewsRequest._(); + static $pb.GeneratedMessage $_createMessage() => ReactNewsRequest._(); + @$core.override + ReactNewsRequest createEmptyInstance() => ReactNewsRequest._(); + @$core.pragma('dart2js:noInline') + static ReactNewsRequest getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(ReactNewsRequest.$_createMessage); + static ReactNewsRequest? _defaultInstance; + + /// Hex-encoded 12-byte ItemID of the story or comment. + @$pb.TagNumber(1) + $core.String get parentId => $_getSZ(0); + @$pb.TagNumber(1) + set parentId($core.String value) => $_setString(0, value); + @$pb.TagNumber(1) + $core.bool hasParentId() => $_has(0); + @$pb.TagNumber(1) + void clearParentId() => $_clearField(1); + + @$pb.TagNumber(2) + $core.String get emoji => $_getSZ(1); + @$pb.TagNumber(2) + set emoji($core.String value) => $_setString(1, value); + @$pb.TagNumber(2) + $core.bool hasEmoji() => $_has(1); + @$pb.TagNumber(2) + void clearEmoji() => $_clearField(2); + + /// Fee of the reaction. It adds to the total of the emoji. + @$pb.TagNumber(3) + $fixnum.Int64 get feeSats => $_getI64(2); + @$pb.TagNumber(3) + set feeSats($fixnum.Int64 value) => $_setInt64(2, value); + @$pb.TagNumber(3) + $core.bool hasFeeSats() => $_has(2); + @$pb.TagNumber(3) + void clearFeeSats() => $_clearField(3); +} + +class ReactNewsResponse extends $pb.GeneratedMessage { + factory ReactNewsResponse({ + $core.String? txid, + }) { + final result = ReactNewsResponse._(); + if (txid != null) result.txid = txid; + return result; + } + + ReactNewsResponse._(); + + factory ReactNewsResponse.fromBuffer($core.List<$core.int> data, + [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => + ReactNewsResponse()..mergeFromBuffer(data, registry); + factory ReactNewsResponse.fromJson($core.String json, + [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => + ReactNewsResponse()..mergeFromJson(json, registry); + + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ReactNewsResponse', + package: const $pb.PackageName(_omitMessageNames ? '' : 'misc.v1'), + createEmptyInstance: ReactNewsResponse.$_createMessage) + ..aOS(1, _omitFieldNames ? '' : 'txid') + ..hasRequiredFields = false; + + @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') + ReactNewsResponse clone() => deepCopy(); + @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') + ReactNewsResponse copyWith(void Function(ReactNewsResponse) updates) => + super.copyWith((message) => updates(message as ReactNewsResponse)) as ReactNewsResponse; + + @$core.override + $pb.BuilderInfo get info_ => _i; + + @$core.pragma('dart2js:noInline') + @$core.Deprecated('Use ReactNewsResponse() / ReactNewsResponse.new instead') + static ReactNewsResponse create() => ReactNewsResponse._(); + static $pb.GeneratedMessage $_createMessage() => ReactNewsResponse._(); + @$core.override + ReactNewsResponse createEmptyInstance() => ReactNewsResponse._(); + @$core.pragma('dart2js:noInline') + static ReactNewsResponse getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(ReactNewsResponse.$_createMessage); + static ReactNewsResponse? _defaultInstance; + + @$pb.TagNumber(1) + $core.String get txid => $_getSZ(0); + @$pb.TagNumber(1) + set txid($core.String value) => $_setString(0, value); + @$pb.TagNumber(1) + $core.bool hasTxid() => $_has(0); + @$pb.TagNumber(1) + void clearTxid() => $_clearField(1); +} + class ListCommentsRequest extends $pb.GeneratedMessage { factory ListCommentsRequest({ $core.String? itemId, @@ -2452,6 +2672,10 @@ class MiscServiceApi { $async.Future listComments($pb.ClientContext? ctx, ListCommentsRequest request) => _client.invoke(ctx, 'MiscService', 'ListComments', request, ListCommentsResponse()); + /// Broadcasts a Reaction (CoinNews Reaction, 0x07) on an Item. + $async.Future reactNews($pb.ClientContext? ctx, ReactNewsRequest request) => + _client.invoke(ctx, 'MiscService', 'ReactNews', request, ReactNewsResponse()); + /// The fee that the active wallet pays for a story, a comment or a topic with no fee /// choice. Broadcasts nothing. $async.Future estimateNewsFee($pb.ClientContext? ctx, EstimateNewsFeeRequest request) => diff --git a/sidechain_core/lib/gen/misc/v1/misc.pbenum.dart b/sidechain_core/lib/gen/misc/v1/misc.pbenum.dart index 7265989397..a7d54d9dbf 100644 --- a/sidechain_core/lib/gen/misc/v1/misc.pbenum.dart +++ b/sidechain_core/lib/gen/misc/v1/misc.pbenum.dart @@ -44,15 +44,17 @@ class NewsAction extends $pb.ProtobufEnum { static const NewsAction NEWS_ACTION_COMMENT = NewsAction._(2, _omitEnumNames ? '' : 'NEWS_ACTION_COMMENT'); static const NewsAction NEWS_ACTION_STORY = NewsAction._(3, _omitEnumNames ? '' : 'NEWS_ACTION_STORY'); static const NewsAction NEWS_ACTION_TOPIC = NewsAction._(4, _omitEnumNames ? '' : 'NEWS_ACTION_TOPIC'); + static const NewsAction NEWS_ACTION_REACTION = NewsAction._(5, _omitEnumNames ? '' : 'NEWS_ACTION_REACTION'); static const $core.List values = [ NEWS_ACTION_UNSPECIFIED, NEWS_ACTION_COMMENT, NEWS_ACTION_STORY, NEWS_ACTION_TOPIC, + NEWS_ACTION_REACTION, ]; - static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 4); + static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 5); static NewsAction? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const NewsAction._(super.value, super.name); diff --git a/sidechain_core/lib/gen/misc/v1/misc.pbjson.dart b/sidechain_core/lib/gen/misc/v1/misc.pbjson.dart index 5098830e2b..25f2b96769 100644 --- a/sidechain_core/lib/gen/misc/v1/misc.pbjson.dart +++ b/sidechain_core/lib/gen/misc/v1/misc.pbjson.dart @@ -46,6 +46,7 @@ const NewsAction$json = { {'1': 'NEWS_ACTION_COMMENT', '2': 2}, {'1': 'NEWS_ACTION_STORY', '2': 3}, {'1': 'NEWS_ACTION_TOPIC', '2': 4}, + {'1': 'NEWS_ACTION_REACTION', '2': 5}, ], '4': [ {'1': 1, '2': 1}, @@ -57,7 +58,7 @@ const NewsAction$json = { final $typed_data.Uint8List newsActionDescriptor = $convert.base64Decode('CgpOZXdzQWN0aW9uEhsKF05FV1NfQUNUSU9OX1VOU1BFQ0lGSUVEEAASFwoTTkVXU19BQ1RJT0' '5fQ09NTUVOVBACEhUKEU5FV1NfQUNUSU9OX1NUT1JZEAMSFQoRTkVXU19BQ1RJT05fVE9QSUMQ' - 'BCIECAEQASoQTkVXU19BQ1RJT05fVk9URQ=='); + 'BBIYChRORVdTX0FDVElPTl9SRUFDVElPThAFIgQIARABKhBORVdTX0FDVElPTl9WT1RF'); @$core.Deprecated('Use listOPReturnRequestDescriptor instead') const ListOPReturnRequest$json = { @@ -241,6 +242,7 @@ const EstimateNewsFeeRequest$json = { {'1': 'nsfw', '3': 7, '4': 1, '5': 8, '10': 'nsfw'}, {'1': 'topic_name', '3': 8, '4': 1, '5': 9, '10': 'topicName'}, {'1': 'retention_days', '3': 9, '4': 1, '5': 5, '10': 'retentionDays'}, + {'1': 'emoji', '3': 10, '4': 1, '5': 9, '10': 'emoji'}, ], }; @@ -250,7 +252,8 @@ final $typed_data.Uint8List estimateNewsFeeRequestDescriptor = 'FjdGlvblIGYWN0aW9uEhIKBGJvZHkYAiABKAlSBGJvZHkSGgoIaGVhZGxpbmUYAyABKAlSCGhl' 'YWRsaW5lEhAKA3VybBgEIAEoCVIDdXJsEhIKBGxhbmcYBSABKAlSBGxhbmcSGAoHc3VidHlwZR' 'gGIAEoBVIHc3VidHlwZRISCgRuc2Z3GAcgASgIUgRuc2Z3Eh0KCnRvcGljX25hbWUYCCABKAlS' - 'CXRvcGljTmFtZRIlCg5yZXRlbnRpb25fZGF5cxgJIAEoBVINcmV0ZW50aW9uRGF5cw=='); + 'CXRvcGljTmFtZRIlCg5yZXRlbnRpb25fZGF5cxgJIAEoBVINcmV0ZW50aW9uRGF5cxIUCgVlbW' + '9qaRgKIAEoCVIFZW1vamk='); @$core.Deprecated('Use estimateNewsFeeResponseDescriptor instead') const EstimateNewsFeeResponse$json = { @@ -302,6 +305,8 @@ const CoinNews$json = { {'1': 'vout', '3': 15, '4': 1, '5': 13, '10': 'vout'}, {'1': 'outdated', '3': 16, '4': 1, '5': 8, '10': 'outdated'}, {'1': 'pending', '3': 17, '4': 1, '5': 8, '10': 'pending'}, + {'1': 'reactions', '3': 18, '4': 3, '5': 11, '6': '.misc.v1.Reaction', '10': 'reactions'}, + {'1': 'max_comment_chars', '3': 19, '4': 1, '5': 5, '10': 'maxCommentChars'}, ], '9': [ {'1': 8, '2': 9}, @@ -319,8 +324,24 @@ final $typed_data.Uint8List coinNewsDescriptor = 'VmLlRpbWVzdGFtcFIKY3JlYXRlVGltZRIXCgdpdGVtX2lkGAcgASgJUgZpdGVtSWQSEAoDdXJs' 'GAsgASgJUgN1cmwSGAoHc3VidHlwZRgMIAEoBVIHc3VidHlwZRISCgRuc2Z3GA0gASgIUgRuc2' 'Z3EhIKBHR4aWQYDiABKAlSBHR4aWQSEgoEdm91dBgPIAEoDVIEdm91dBIaCghvdXRkYXRlZBgQ' - 'IAEoCFIIb3V0ZGF0ZWQSGAoHcGVuZGluZxgRIAEoCFIHcGVuZGluZ0oECAgQCUoECAkQCkoECA' - 'oQC1IHdXB2b3Rlc1IJZG93bnZvdGVzUgVzY29yZQ=='); + 'IAEoCFIIb3V0ZGF0ZWQSGAoHcGVuZGluZxgRIAEoCFIHcGVuZGluZxIvCglyZWFjdGlvbnMYEi' + 'ADKAsyES5taXNjLnYxLlJlYWN0aW9uUglyZWFjdGlvbnMSKgoRbWF4X2NvbW1lbnRfY2hhcnMY' + 'EyABKAVSD21heENvbW1lbnRDaGFyc0oECAgQCUoECAkQCkoECAoQC1IHdXB2b3Rlc1IJZG93bn' + 'ZvdGVzUgVzY29yZQ=='); + +@$core.Deprecated('Use reactionDescriptor instead') +const Reaction$json = { + '1': 'Reaction', + '2': [ + {'1': 'emoji', '3': 1, '4': 1, '5': 9, '10': 'emoji'}, + {'1': 'fee_sats', '3': 2, '4': 1, '5': 3, '10': 'feeSats'}, + ], +}; + +/// Descriptor for `Reaction`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List reactionDescriptor = + $convert.base64Decode('CghSZWFjdGlvbhIUCgVlbW9qaRgBIAEoCVIFZW1vamkSGQoIZmVlX3NhdHMYAiABKANSB2ZlZV' + 'NhdHM='); @$core.Deprecated('Use listCoinNewsResponseDescriptor instead') const ListCoinNewsResponse$json = { @@ -345,17 +366,20 @@ const CommentNewsRequest$json = { {'1': 'url', '3': 3, '4': 1, '5': 9, '10': 'url'}, {'1': 'lang', '3': 4, '4': 1, '5': 9, '10': 'lang'}, {'1': 'reply_quote', '3': 5, '4': 1, '5': 9, '10': 'replyQuote'}, - {'1': 'fee_sat_per_vbyte', '3': 6, '4': 1, '5': 4, '10': 'feeSatPerVbyte'}, {'1': 'fee_sats', '3': 7, '4': 1, '5': 4, '10': 'feeSats'}, ], + '9': [ + {'1': 6, '2': 7}, + ], + '10': ['fee_sat_per_vbyte'], }; /// Descriptor for `CommentNewsRequest`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List commentNewsRequestDescriptor = $convert.base64Decode('ChJDb21tZW50TmV3c1JlcXVlc3QSGwoJcGFyZW50X2lkGAEgASgJUghwYXJlbnRJZBISCgRib2' 'R5GAIgASgJUgRib2R5EhAKA3VybBgDIAEoCVIDdXJsEhIKBGxhbmcYBCABKAlSBGxhbmcSHwoL' - 'cmVwbHlfcXVvdGUYBSABKAlSCnJlcGx5UXVvdGUSKQoRZmVlX3NhdF9wZXJfdmJ5dGUYBiABKA' - 'RSDmZlZVNhdFBlclZieXRlEhkKCGZlZV9zYXRzGAcgASgEUgdmZWVTYXRz'); + 'cmVwbHlfcXVvdGUYBSABKAlSCnJlcGx5UXVvdGUSGQoIZmVlX3NhdHMYByABKARSB2ZlZVNhdH' + 'NKBAgGEAdSEWZlZV9zYXRfcGVyX3ZieXRl'); @$core.Deprecated('Use commentNewsResponseDescriptor instead') const CommentNewsResponse$json = { @@ -369,6 +393,33 @@ const CommentNewsResponse$json = { final $typed_data.Uint8List commentNewsResponseDescriptor = $convert.base64Decode('ChNDb21tZW50TmV3c1Jlc3BvbnNlEhIKBHR4aWQYASABKAlSBHR4aWQ='); +@$core.Deprecated('Use reactNewsRequestDescriptor instead') +const ReactNewsRequest$json = { + '1': 'ReactNewsRequest', + '2': [ + {'1': 'parent_id', '3': 1, '4': 1, '5': 9, '10': 'parentId'}, + {'1': 'emoji', '3': 2, '4': 1, '5': 9, '10': 'emoji'}, + {'1': 'fee_sats', '3': 3, '4': 1, '5': 4, '10': 'feeSats'}, + ], +}; + +/// Descriptor for `ReactNewsRequest`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List reactNewsRequestDescriptor = + $convert.base64Decode('ChBSZWFjdE5ld3NSZXF1ZXN0EhsKCXBhcmVudF9pZBgBIAEoCVIIcGFyZW50SWQSFAoFZW1vam' + 'kYAiABKAlSBWVtb2ppEhkKCGZlZV9zYXRzGAMgASgEUgdmZWVTYXRz'); + +@$core.Deprecated('Use reactNewsResponseDescriptor instead') +const ReactNewsResponse$json = { + '1': 'ReactNewsResponse', + '2': [ + {'1': 'txid', '3': 1, '4': 1, '5': 9, '10': 'txid'}, + ], +}; + +/// Descriptor for `ReactNewsResponse`. Decode as a `google.protobuf.DescriptorProto`. +final $typed_data.Uint8List reactNewsResponseDescriptor = + $convert.base64Decode('ChFSZWFjdE5ld3NSZXNwb25zZRISCgR0eGlkGAEgASgJUgR0eGlk'); + @$core.Deprecated('Use listCommentsRequestDescriptor instead') const ListCommentsRequest$json = { '1': 'ListCommentsRequest', @@ -553,6 +604,7 @@ const $core.Map<$core.String, $core.dynamic> MiscServiceBase$json = { {'1': 'ListCoinNews', '2': '.misc.v1.ListCoinNewsRequest', '3': '.misc.v1.ListCoinNewsResponse'}, {'1': 'CommentNews', '2': '.misc.v1.CommentNewsRequest', '3': '.misc.v1.CommentNewsResponse'}, {'1': 'ListComments', '2': '.misc.v1.ListCommentsRequest', '3': '.misc.v1.ListCommentsResponse'}, + {'1': 'ReactNews', '2': '.misc.v1.ReactNewsRequest', '3': '.misc.v1.ReactNewsResponse'}, {'1': 'EstimateNewsFee', '2': '.misc.v1.EstimateNewsFeeRequest', '3': '.misc.v1.EstimateNewsFeeResponse'}, {'1': 'TimestampFile', '2': '.misc.v1.TimestampFileRequest', '3': '.misc.v1.TimestampFileResponse'}, {'1': 'ListTimestamps', '2': '.google.protobuf.Empty', '3': '.misc.v1.ListTimestampsResponse'}, @@ -577,11 +629,14 @@ const $core.Map<$core.String, $core.Map<$core.String, $core.dynamic>> MiscServic '.misc.v1.ListCoinNewsRequest': ListCoinNewsRequest$json, '.misc.v1.ListCoinNewsResponse': ListCoinNewsResponse$json, '.misc.v1.CoinNews': CoinNews$json, + '.misc.v1.Reaction': Reaction$json, '.misc.v1.CommentNewsRequest': CommentNewsRequest$json, '.misc.v1.CommentNewsResponse': CommentNewsResponse$json, '.misc.v1.ListCommentsRequest': ListCommentsRequest$json, '.misc.v1.ListCommentsResponse': ListCommentsResponse$json, '.misc.v1.Comment': Comment$json, + '.misc.v1.ReactNewsRequest': ReactNewsRequest$json, + '.misc.v1.ReactNewsResponse': ReactNewsResponse$json, '.misc.v1.EstimateNewsFeeRequest': EstimateNewsFeeRequest$json, '.misc.v1.EstimateNewsFeeResponse': EstimateNewsFeeResponse$json, '.misc.v1.TimestampFileRequest': TimestampFileRequest$json, @@ -606,10 +661,11 @@ final $typed_data.Uint8List miscServiceDescriptor = '5OZXdzUmVxdWVzdBodLm1pc2MudjEuTGlzdENvaW5OZXdzUmVzcG9uc2USSAoLQ29tbWVudE5l' 'd3MSGy5taXNjLnYxLkNvbW1lbnROZXdzUmVxdWVzdBocLm1pc2MudjEuQ29tbWVudE5ld3NSZX' 'Nwb25zZRJLCgxMaXN0Q29tbWVudHMSHC5taXNjLnYxLkxpc3RDb21tZW50c1JlcXVlc3QaHS5t' - 'aXNjLnYxLkxpc3RDb21tZW50c1Jlc3BvbnNlElQKD0VzdGltYXRlTmV3c0ZlZRIfLm1pc2Mudj' - 'EuRXN0aW1hdGVOZXdzRmVlUmVxdWVzdBogLm1pc2MudjEuRXN0aW1hdGVOZXdzRmVlUmVzcG9u' - 'c2USTgoNVGltZXN0YW1wRmlsZRIdLm1pc2MudjEuVGltZXN0YW1wRmlsZVJlcXVlc3QaHi5taX' - 'NjLnYxLlRpbWVzdGFtcEZpbGVSZXNwb25zZRJJCg5MaXN0VGltZXN0YW1wcxIWLmdvb2dsZS5w' - 'cm90b2J1Zi5FbXB0eRofLm1pc2MudjEuTGlzdFRpbWVzdGFtcHNSZXNwb25zZRJUCg9WZXJpZn' - 'lUaW1lc3RhbXASHy5taXNjLnYxLlZlcmlmeVRpbWVzdGFtcFJlcXVlc3QaIC5taXNjLnYxLlZl' - 'cmlmeVRpbWVzdGFtcFJlc3BvbnNl'); + 'aXNjLnYxLkxpc3RDb21tZW50c1Jlc3BvbnNlEkIKCVJlYWN0TmV3cxIZLm1pc2MudjEuUmVhY3' + 'ROZXdzUmVxdWVzdBoaLm1pc2MudjEuUmVhY3ROZXdzUmVzcG9uc2USVAoPRXN0aW1hdGVOZXdz' + 'RmVlEh8ubWlzYy52MS5Fc3RpbWF0ZU5ld3NGZWVSZXF1ZXN0GiAubWlzYy52MS5Fc3RpbWF0ZU' + '5ld3NGZWVSZXNwb25zZRJOCg1UaW1lc3RhbXBGaWxlEh0ubWlzYy52MS5UaW1lc3RhbXBGaWxl' + 'UmVxdWVzdBoeLm1pc2MudjEuVGltZXN0YW1wRmlsZVJlc3BvbnNlEkkKDkxpc3RUaW1lc3RhbX' + 'BzEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5Gh8ubWlzYy52MS5MaXN0VGltZXN0YW1wc1Jlc3Bv' + 'bnNlElQKD1ZlcmlmeVRpbWVzdGFtcBIfLm1pc2MudjEuVmVyaWZ5VGltZXN0YW1wUmVxdWVzdB' + 'ogLm1pc2MudjEuVmVyaWZ5VGltZXN0YW1wUmVzcG9uc2U='); diff --git a/sidechain_core/lib/gen/misc/v1/misc.pbserver.dart b/sidechain_core/lib/gen/misc/v1/misc.pbserver.dart index 6e41f91750..3e60274753 100644 --- a/sidechain_core/lib/gen/misc/v1/misc.pbserver.dart +++ b/sidechain_core/lib/gen/misc/v1/misc.pbserver.dart @@ -31,6 +31,7 @@ abstract class MiscServiceBase extends $pb.GeneratedService { $async.Future<$2.ListCoinNewsResponse> listCoinNews($pb.ServerContext ctx, $2.ListCoinNewsRequest request); $async.Future<$2.CommentNewsResponse> commentNews($pb.ServerContext ctx, $2.CommentNewsRequest request); $async.Future<$2.ListCommentsResponse> listComments($pb.ServerContext ctx, $2.ListCommentsRequest request); + $async.Future<$2.ReactNewsResponse> reactNews($pb.ServerContext ctx, $2.ReactNewsRequest request); $async.Future<$2.EstimateNewsFeeResponse> estimateNewsFee($pb.ServerContext ctx, $2.EstimateNewsFeeRequest request); $async.Future<$2.TimestampFileResponse> timestampFile($pb.ServerContext ctx, $2.TimestampFileRequest request); $async.Future<$2.ListTimestampsResponse> listTimestamps($pb.ServerContext ctx, $1.Empty request); @@ -56,6 +57,8 @@ abstract class MiscServiceBase extends $pb.GeneratedService { return $2.CommentNewsRequest(); case 'ListComments': return $2.ListCommentsRequest(); + case 'ReactNews': + return $2.ReactNewsRequest(); case 'EstimateNewsFee': return $2.EstimateNewsFeeRequest(); case 'TimestampFile': @@ -90,6 +93,8 @@ abstract class MiscServiceBase extends $pb.GeneratedService { return commentNews(ctx, request as $2.CommentNewsRequest); case 'ListComments': return listComments(ctx, request as $2.ListCommentsRequest); + case 'ReactNews': + return reactNews(ctx, request as $2.ReactNewsRequest); case 'EstimateNewsFee': return estimateNewsFee(ctx, request as $2.EstimateNewsFeeRequest); case 'TimestampFile': diff --git a/sidechain_core/lib/rpcs/bitwindow_api.dart b/sidechain_core/lib/rpcs/bitwindow_api.dart index 61984185e9..ab4a5c4371 100644 --- a/sidechain_core/lib/rpcs/bitwindow_api.dart +++ b/sidechain_core/lib/rpcs/bitwindow_api.dart @@ -1392,16 +1392,21 @@ abstract class MiscAPI { bool nsfw = false, String topicName = '', int retentionDays = 0, + String emoji = '', }); + + /// Comments on a story or a comment. The fee must be at least the fee of the root story. Future commentNews( String parentId, String body, { + required int feeSats, String? url, String? lang, String? replyQuote, - int? feeSatPerVbyte, - int? feeSats, }); + + /// Adds feeSats to the total of the emoji on an item. + Future reactNews(String parentId, String emoji, {required int feeSats}); Future listComments(String itemId); Future timestampFile(String filename, List fileData); Future> listTimestamps(); @@ -1479,6 +1484,7 @@ class _MiscAPILive implements MiscAPI { bool nsfw = false, String topicName = '', int retentionDays = 0, + String emoji = '', }) async { try { final response = await _client.estimateNewsFee( @@ -1491,6 +1497,7 @@ class _MiscAPILive implements MiscAPI { nsfw: nsfw, topicName: topicName, retentionDays: retentionDays, + emoji: emoji, ), ); return NewsFeeEstimate( @@ -1508,16 +1515,16 @@ class _MiscAPILive implements MiscAPI { Future commentNews( String parentId, String body, { + required int feeSats, String? url, String? lang, String? replyQuote, - int? feeSatPerVbyte, - int? feeSats, }) async { try { final request = CommentNewsRequest() ..parentId = parentId - ..body = body; + ..body = body + ..feeSats = Int64(feeSats); if (url != null) { request.url = url; } @@ -1528,20 +1535,25 @@ class _MiscAPILive implements MiscAPI { request.replyQuote = replyQuote; } - if (feeSatPerVbyte != null) { - request.feeSatPerVbyte = Int64(feeSatPerVbyte); - } else if (feeSats != null) { - request.feeSats = Int64(feeSats); - } - - final response = await _client.commentNews(request); - return response; + return await _client.commentNews(request); } catch (e) { final error = 'could not comment on news: ${extractConnectException(e)}'; throw BitwindowException(error); } } + @override + Future reactNews(String parentId, String emoji, {required int feeSats}) async { + try { + return await _client.reactNews( + ReactNewsRequest(parentId: parentId, emoji: emoji, feeSats: Int64(feeSats)), + ); + } catch (e) { + final error = 'could not react to news: ${extractConnectException(e)}'; + throw BitwindowException(error); + } + } + @override Future listComments(String itemId) async { try { diff --git a/sidechain_core/lib/settings/news_warning_settings.dart b/sidechain_core/lib/settings/news_warning_settings.dart deleted file mode 100644 index 10d467f68e..0000000000 --- a/sidechain_core/lib/settings/news_warning_settings.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'package:sidechain_core/sidechain_core.dart'; - -/// Set once the user has been told that commenting spends money on chain. -class CommentWarningSeenSetting extends SettingValue { - CommentWarningSeenSetting({super.newValue}); - - @override - String get key => 'news_comment_warning_seen'; - - @override - bool defaultValue() => false; - - @override - String toJson() { - return value.toString(); - } - - @override - bool? fromJson(String jsonString) { - return jsonString == 'true'; - } - - @override - SettingValue withValue([bool? value]) { - return CommentWarningSeenSetting(newValue: value); - } -} diff --git a/sidechain_core/lib/sidechain_core.dart b/sidechain_core/lib/sidechain_core.dart index 2da13be67c..18c159e680 100644 --- a/sidechain_core/lib/sidechain_core.dart +++ b/sidechain_core/lib/sidechain_core.dart @@ -201,7 +201,6 @@ export 'settings/font_settings.dart'; export 'settings/font_size_settings.dart'; export 'settings/hash_plaintext_settings.dart'; export 'settings/secure_store.dart'; -export 'settings/news_warning_settings.dart'; export 'settings/bitwindow_settings.dart'; export 'settings/notification_history_setting.dart'; export 'settings/theme_settings.dart'; diff --git a/thunder/pubspec.yaml b/thunder/pubspec.yaml index a85e5147da..a63b761bfb 100644 --- a/thunder/pubspec.yaml +++ b/thunder/pubspec.yaml @@ -2,7 +2,7 @@ name: thunder description: UI for Drivechain (BIP300/301) based sidechains publish_to: "none" # Remove this line if you wish to publish to pub.dev -version: 1.0.398 +version: 1.0.399 environment: sdk: 3.13.7 diff --git a/truthcoin/pubspec.yaml b/truthcoin/pubspec.yaml index 244921946c..76c57dea91 100644 --- a/truthcoin/pubspec.yaml +++ b/truthcoin/pubspec.yaml @@ -2,7 +2,7 @@ name: truthcoin description: UI for Bitcoin Hivemind prediction market sidechain publish_to: "none" # Remove this line if you wish to publish to pub.dev -version: 1.0.269 +version: 1.0.270 environment: sdk: 3.13.7 diff --git a/zside/pubspec.yaml b/zside/pubspec.yaml index c94481d656..bfb950cdf4 100644 --- a/zside/pubspec.yaml +++ b/zside/pubspec.yaml @@ -2,7 +2,7 @@ name: zside description: UI for Drivechain (BIP300/301) based sidechains publish_to: "none" # Remove this line if you wish to publish to pub.dev -version: 1.0.395 +version: 1.0.396 environment: sdk: 3.13.7