1 #!/usr/bin/env bash
2 #
3 # Copyright (c) 2017-present The Bitcoin Core developers
4 # Distributed under the MIT software license, see the accompanying
5 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 7 export LC_ALL=C
8 #network interface on which to limit traffic
9 IF="eth0"
10 #limit of the network interface in question
11 LINKCEIL="1gbit"
12 #limit outbound Bitcoin protocol traffic to this rate
13 LIMIT="160kbit"
14 #defines the IPv4 address space for which you wish to disable rate limiting
15 LOCALNET_V4="192.168.0.0/16"
16 #defines the IPv6 address space for which you wish to disable rate limiting
17 LOCALNET_V6="fe80::/10"
18 19 #delete existing rules ('Error: Cannot delete qdisc with handle of zero.' means there weren't any.)
20 tc qdisc del dev ${IF} root
21 22 #add root class
23 tc qdisc add dev ${IF} root handle 1: htb default 10
24 25 #add parent class
26 tc class add dev ${IF} parent 1: classid 1:1 htb rate ${LINKCEIL} ceil ${LINKCEIL}
27 28 #add our two classes. one unlimited, another limited
29 tc class add dev ${IF} parent 1:1 classid 1:10 htb rate ${LINKCEIL} ceil ${LINKCEIL} prio 0
30 tc class add dev ${IF} parent 1:1 classid 1:11 htb rate ${LIMIT} ceil ${LIMIT} prio 1
31 32 #add handles to our classes so packets marked with <x> go into the class with "... handle <x> fw ..."
33 tc filter add dev ${IF} parent 1: protocol ip prio 1 handle 1 fw classid 1:10
34 tc filter add dev ${IF} parent 1: protocol ip prio 2 handle 2 fw classid 1:11
35 36 if [ -n "${LOCALNET_V6}" ] ; then
37 # v6 cannot have the same priority value as v4
38 tc filter add dev ${IF} parent 1: protocol ipv6 prio 3 handle 1 fw classid 1:10
39 tc filter add dev ${IF} parent 1: protocol ipv6 prio 4 handle 2 fw classid 1:11
40 fi
41 42 #delete any existing rules
43 #disable for now
44 #ret=0
45 #while [ $ret -eq 0 ]; do
46 # iptables -t mangle -D OUTPUT 1
47 # ret=$?
48 #done
49 50 #limit outgoing traffic to and from port 8333. but not when dealing with a host on the local network
51 # (defined by $LOCALNET_V4 and $LOCALNET_V6)
52 # --set-mark marks packages matching these criteria with the number "2" (v4)
53 # --set-mark marks packages matching these criteria with the number "4" (v6)
54 # these packets are filtered by the tc filter with "handle 2"
55 # this filter sends the packages into the 1:11 class, and this class is limited to ${LIMIT}
56 iptables -t mangle -A OUTPUT -p tcp -m tcp --dport 8333 ! -d ${LOCALNET_V4} -j MARK --set-mark 0x2
57 iptables -t mangle -A OUTPUT -p tcp -m tcp --sport 8333 ! -d ${LOCALNET_V4} -j MARK --set-mark 0x2
58 59 if [ -n "${LOCALNET_V6}" ] ; then
60 ip6tables -t mangle -A OUTPUT -p tcp -m tcp --dport 8333 ! -d ${LOCALNET_V6} -j MARK --set-mark 0x4
61 ip6tables -t mangle -A OUTPUT -p tcp -m tcp --sport 8333 ! -d ${LOCALNET_V6} -j MARK --set-mark 0x4
62 fi
63